[英]Method PUT is not allowed by Access-Control-Allow-Methods in preflight response FLASK CORS
GETs are working right. GET工作正常。 I can't seem to make PUT work and I fear POST is not working as well.
我似乎无法使PUT正常工作,而且我担心POST也无法正常工作。
Kept on having the error 继续发生错误
Access to XMLHttpRequest at '<...>' from origin 'https://localhost:3000' has been blocked by CORS policy: Method PUT is not allowed by Access-Control-Allow-Methods in preflight response.
I have a local webapp that calls on an external api which means CORS will be one of the hurdles I should tackle. 我有一个本地Web应用程序,该应用程序需要一个外部api,这意味着CORS将是我应该解决的障碍之一。
Here's my flask code. 这是我的烧瓶代码。
@blueprint.route('/profiles/<oi_id>', methods=['POST'])
@cross_origin(send_wildcard=True, methods=['POST', 'OPTIONS'])
def create_checkin_profile(oi_id):
return jsonify(cph.create_owner_profile_info(oi_id, json.loads(request.data)))
@blueprint.route('/profiles/<oi_id>', methods=['PUT'])
@cross_origin(send_wildcard=True, methods=['PUT', 'OPTIONS'])
def edit_checkin_profile(oi_id):
return jsonify(cph.edit_owner_profile_info(oi_id, json.loads(request.data)))
It's quite confusing since I'm pretty sure I allowed PUT. 因为我很确定我允许PUT,所以这非常令人困惑。 I'm using axios for this on a react app.
我在React应用程序上为此使用axios。 Here's my call-api function.
这是我的call-api函数。
axios({
method: 'PUT',
url: url,
timeout: 3000,
data: data,
headers: {
"Access-Control-Allow-Origin": "*",
"Content-Type": "application/json",
Accept: "application/json",
},
});
Alright I fixed this. 好吧,我解决了这个问题。 Apparently according to the docs I have to specify "Content-Type" on the cross origin requests.
显然,根据文档,我必须在跨源请求中指定“ Content-Type”。 Like so:
像这样:
@cross_origin(allow_headers=['Content-Type'])
Don't be fooled by the default of allow all. 默认为allow all,请不要上当。 You need to specify this apparently.
您显然需要指定此。
I have to remove unnecessary headers such as Accept and Access-Control-Allow-Origin. 我必须删除不必要的标头,例如Accept和Access-Control-Allow-Origin。 Updating my axios like so:
像这样更新我的axios:
axios({
method: 'PUT',
url: url,
timeout: 3000,
data: data,
headers: {
"Content-Type": "application/json",
},
});
BONUS: 奖金:
I ran into a problem if my api calls returned a non 200 response with preflight request, the response body becomes null. 如果我的api调用返回了一个非200的预检请求响应,则我遇到了一个问题,响应主体变为null。 I just added these lines of code on my main application.
我只是在主应用程序中添加了这些代码行。 I needed the body for the details of the error is there.
我需要正文以获取错误的详细信息。
@app.after_request
def set_cors_header(response):
response.headers['Access-Control-Allow-Origin'] = '*'
return response
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.