Axios,对Flask的POST请求

时间:2017-07-28 12:07:54

标签: flask axios

我尝试使用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": "*"}})

2 个答案:

答案 0 :(得分:1)

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

答案 1 :(得分:0)

If anyone else is stuck, be sure to check your before and after request methods. My problem was this:

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

So then this would raise an exception on any request, including an OPTIONS method. Of course, the fix is easy:

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