Axios,POST 向 Flask 请求

Axios, POST request to Flask

我尝试使用 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. 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' 因此不允许访问。

为什么?我会按照建议设置 header。

这里是解决方案

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

您需要为 Flask 应用添加 CORS 支持。在此处查看相关威胁: 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/.

如果其他人遇到问题,请务必检查您的 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!")

那么这将引发 any 请求的异常,包括 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!")