Axios,对 Flask 的 POST 请求 [英] Axios, POST request to Flask

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

问题描述

我尝试使用 axios 对烧瓶服务器进行 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"标头.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天全站免登陆