Python/Flask Rest API not passing preflight w/CORS

Viewed 5235

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.

2 Answers
Related