I'm running a Flask-Restful API locally and sending a POST request containing JSON from a different port. 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 "*". GET works fine, it's just POST that gives this error. What could be going wrong? If relevant, for the frontend I'm using react and requesting through axios.
Postman simply doesn't care about CORS headers. So CORS is just a browser concept and not a strong security mechanism. It allows you to restrict which other web apps may use your backend resources but that's all. Definitely better than nothing but not something you should use as a content-protection mechanism!
In order to fix CORS, you need to make sure that the API is sending proper headers (Access-Control-Allow-*). That's why it's not something you can fix in the UI, and that's why it only causes an issue in the browser and not via curl: because it's the browser that checks and eventually blocks the calls.
To resolve a CORS error from an API Gateway REST API or HTTP API, you must reconfigure the API to meet the CORS standard. For more information on configuring CORS for REST APIs, see Configuring CORS for a REST API resource. For HTTP APIs, see Configuring CORS for an HTTP API.
You have to add CORS(app, resources={r"/*": {"origins": "*"}})
into your flask app.
Hope that solves the issue.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With