Axios,向Flask发送POST请求

5

我试图使用axios向flask服务器进行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'无法访问。
为什么?我已经按建议设置了标头。
以下是解决方案:
from flask_cors import CORS, cross_origin
app = Flask(__name__)
cors = CORS(app, resources={r"/YOURAPP/*": {"origins": "*"}})
2个回答

5

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!")

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接