Axios,对Flask的POST请求

问题描述 投票:1回答:2

我尝试使用axios对烧瓶服务器进行POST:

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的一部分

...
data = request.get_json(silent=True)
item = {'label': data.get('label'), 'text': data.get('text')}
print item
...

但是,我最终会得到以下错误:

XMLHttpRequest无法加载http://127.0.0.1:5000/test。对预检请求的响应未通过访问控制检查:请求的资源上不存在“Access-Control-Allow-Origin”标头。因此,'http://localhost:3000'原产地不允许进入。

为什么?我LL按照建议设置标题。

这里的解决方案

from flask_cors import CORS, cross_origin app = Flask(__name__) cors = CORS(app, resources={r"/YOURAPP/*": {"origins": "*"}})

flask axios
2个回答
1
投票

您需要为Flask应用添加CORS支持。在这里查看相关威胁:Flask-CORS not working for POST, but working for GET。 Flask的流行CORS扩展可以在这里找到:https://flask-cors.readthedocs.io/en/latest/


0
投票

如果其他人被困,请务必检查您的beforeafter请求方法。我的问题是这样的:

@app.before_request
def oauth_verify(*args, **kwargs):
    """Ensure the oauth authorization header is set"""
    if not _is_oauth_valid():
        return some_custome_error_response("you need oauth!")

那么这会在任何请求上引发异常,包括OPTIONS方法。当然,修复很简单:

@app.before_request
def oauth_verify(*args, **kwargs):
    """Ensure the oauth authorization header is set"""
    if request.method in ['OPTIONS', ]:
        return
    if not _is_oauth_valid():
        return some_custome_error_response("you need oauth!")
© www.soinside.com 2019 - 2024. All rights reserved.