Axios,向Flask发出POST请求 [英] Axios, POST request to Flask

查看:691
本文介绍了Axios,向Flask发出POST请求的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我尝试使用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("http://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无法加载 http://127.0.0.1:5000/test .对预检请求的响应未通过访问控制检查:在所请求的资源上不存在"Access-Control-Allow-Origin"标头.因此,不允许访问来源" http://localhost:3000 ".

XMLHttpRequest cannot load http://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 'http://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扩展名: https://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: https://flask-cors.readthedocs.io/en/latest/.

这篇关于Axios,向Flask发出POST请求的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆