我尝试使用axios对flask服务器进行POST:
I try to make a POST to a flask server using axios:
var config = { headers: { 'Content-Type': 'application/json', 'Access-Control-Allow-Origin': '*'} } axios.post("127.0.0.1:5000/test", { label : "Test" , text : "Test"} , config ) .then(function (response) { console.log(response); }) .catch(function (error) { console.log(error); });现在是Flask的一部分
Now the part of Flask
... data = request.get_json(silent=True) item = {'label': data.get('label'), 'text': data.get('text')} print item ...但是,我将遇到以下错误:
However, I ll end up with the following error:
XMLHttpRequest无法加载 127.0.0.1:5000/test .对预检请求的响应未通过访问控制检查:在所请求的资源上不存在"Access-Control-Allow-Origin"标头.因此,不允许访问来源" localhost:3000 ".
XMLHttpRequest cannot load 127.0.0.1:5000/test. Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'localhost:3000' is therefore not allowed access.
为什么?我会按照建议设置标题.
Why? I LL set the header as suggested.
解决方法
from flask_cors import CORS, cross_origin app = Flask(__name__) cors = CORS(app, resources={r"/YOURAPP/*": {"origins": "*"}})推荐答案
您需要在Flask应用中添加CORS支持.在此处查看相关威胁: Flask-CORS不适用于POST,但为GET工作.可以在以下位置找到Flask的常用CORS扩展名: flask-cors.readthedocs. io/en/latest/.
You need to add CORS support to your Flask app. See a related threat here: Flask-CORS not working for POST, but working for GET. A popular CORS extension for Flask can be found here: flask-cors.readthedocs.io/en/latest/.
更多推荐
Axios,向Flask发出POST请求
发布评论