7

I am trying to get the simplest rest api up that I can in python and I am having trouble. I'm not sure what I am doing wrong, but I think it has something to do with CORS. This is frustrating, as I have used the flask_cors package in order to fix this and it does not appear to work.

In my main.py file i have the following

from flask import Flask
from flask_cors import CORS, cross_origin

app = Flask(__name__)
CORS(app)

import routes.login

if __name__ == '__main__':
    app.run(debug=True)

For my project I have this as my folder structure:

main.py
__init__.py
routes
  __init__.py
  login.py

And i have the following code in login.py

from flask import Flask
from flask_cors import CORS, cross_origin

from main import app
CORS(app)

@app.route('/login', methods=['POST', 'GET'])
@cross_origin()
def login(name, password):
    if request.method == 'POST':
        print('inside login POST')
    if request.method == 'GET':
        print('inside login GET')

I'm currently getting this error:

xhr.js:178 OPTIONS http://localhost:5000/login 404 (NOT FOUND)
dispatchXhrRequest @ xhr.js:178
xhrAdapter @ xhr.js:12
dispatchRequest @ dispatchRequest.js:52
:3000/pictureswapper:1 XMLHttpRequest cannot load http://localhost:5000/login.
 Response for preflight has invalid HTTP status code 404

There is some sort of CORS error, but I really don't know what's going wrong. Any ideas?

EDIT: The only place in the documentation that has anything to say about preflight is here (https://flask-cors.readthedocs.io/en/v1.3.1/index.html?highlight=preflight). If I add

@cross_origin(headers=['Content-Type']) # Send Access-Control-Allow-Headers

It doesn't break the application, but neither does it fix the error.

Peter Weyand
  • 2,159
  • 9
  • 40
  • 72
  • I've also tried to use the method used here: http://flask.pocoo.org/snippets/56/, and referenced in this stackoverflow answer: https://stackoverflow.com/questions/22181384/javascript-no-access-control-allow-origin-header-is-present-on-the-requested, and it does not seem to work either. Same error. – Peter Weyand Jul 09 '17 at 19:11
  • Have you tried the URL in a browser address bar first to ensure it is actually working? – Josh J Jul 09 '17 at 19:59

2 Answers2

3

Revisiting this after a few months.

One of the nasty gotchas in python/flask appears to be that the compiled code will get cached, so if you change something at the entrypoint of the app (ie main.py), and don't delete the binaries that flask export creates then every time you run flask export and recompile it may be using old code!

Make sure to delete (in atom they are the purple 1/0 files -if you have file icons enabled- labeled .pyc) these files if you are getting spooky output.

Peter Weyand
  • 2,159
  • 9
  • 40
  • 72
0

Add OPTIONS to the methods keyword of your route decorator, or remove that keyword altogether.

Josh J
  • 6,813
  • 3
  • 25
  • 47