I am building a REST api in Flask. I handled the DB connection, was able to put JSON data to the browser (using get requests), and then when I tried to test it (when I tried making a POST and GET request from a Node server - react application), it gave me a CORS header error in the console.
I did some research, and found that i need to use flask-cors. I installed it, I imported it and I wrote the following code:
app = Flask(__name__)
cors = CORS(app)
But this didn't work. I also tried using the @cross_origin
decorator but that didn't work either. Then I attempted adding headers to the response itself:
resp.headers.add('Access-Control-Allow-Origin', '*')
but that also didn't work.
I am running the application in a venv
using the built in flask run
command which spits out a local server at ip 127.0.0.1:5000
. I have done the same thing in both C# and PHP (cors handling), and there it worked like a charm. Here I have tried doing it in 3 different ways and it wont work. Any ideas? Could this be because I am running it in development mode, or because of the venv or something? I don't have much experience in backend Python.
This short example using CORS should work. It is adapted from this answer and works for me. I think the app.config
line makes it different from your approach.
from flask import Flask
from flask_cors import CORS, cross_origin
app = Flask(__name__)
cors = CORS(app)
app.config['CORS_HEADERS'] = 'Content-Type'
@app.route("/")
@cross_origin()
def myFunction():
return "Hello world"
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.