简体   繁体   English

Flask-CORS 不适用于 POST,但适用于 GET

[英]Flask-CORS not working for POST, but working for GET

I'm running a Flask-Restful API locally and sending a POST request containing JSON from a different port.我在本地运行 Flask-Restful API 并从不同端口发送包含 JSON 的 POST 请求。 I'm getting the error我收到错误

No 'Access-Control-Allow-Origin' header is present on the requested resource.

However, when I run然而,当我跑

curl --include -X OPTIONS http://localhost:5000/api/comments/3
        --header Access-Control-Request-Method:POST
        --header Access-Control-Request-Headers:Content-Type
        --header Origin:http://localhost:8080

I get我得到

HTTP/1.0 200 OK
Content-Type: text/html; charset=utf-8
Allow: HEAD, GET, POST, OPTIONS
Access-Control-Allow-Origin: http://localhost:8080
Access-Control-Allow-Methods: DELETE, GET, HEAD, OPTIONS, PATCH, POST, PUT
Vary: Origin
Access-Control-Allow-Headers: Content-Type
Content-Length: 0

which shows "Access-Control-Allow-Origin" as "*".将“Access-Control-Allow-Origin”显示为“*”。 GET works fine, it's just POST that gives this error. GET 工作正常,只是 POST 会出现此错误。 What could be going wrong?可能出什么问题了? If relevant, for the frontend I'm using react and requesting through axios.如果相关,对于前端,我正在使用 react 并通过 axios 请求。

You have to add CORS(app, resources={r"/*": {"origins": "*"}}) into your flask app.您必须将CORS(app, resources={r"/*": {"origins": "*"}})到您的烧瓶应用程序中。

Hope that solves the issue.希望能解决问题。

the Flask-Cors docs explain why this might happen Flask-Cors 文档解释了为什么会发生这种情况

"When using JSON cross origin, browsers will issue a pre-flight OPTIONS request for POST requests. In order for browsers to allow POST requests with a JSON content type, you must allow the Content-Type header. The simplest way to do this is to simply set the CORS_HEADERS configuration value on your application: eg" “当使用 JSON 跨域时,浏览器会针对 POST 请求发出预检 OPTIONS 请求。为了让浏览器允许 POST 请求具有 JSON 内容类型,您必须允许 Content-Type 标头。最简单的方法是只需在您的应用程序上设置 CORS_HEADERS 配置值:例如”

https://flask-cors.readthedocs.io/en/1.9.0/ https://flask-cors.readthedocs.io/en/1.9.0/

app.config['CORS_HEADERS'] = 'Content-Type'

In my case, a CORS error raised because of an internal error.就我而言,由于内部错误引发了 CORS 错误。 An error completely unrelated to CORS, which should return 500, was causing this.一个与 CORS 完全无关的错误,它应该返回 500,导致了这个。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM