Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Flask-CORS not working for POST, but working for GET

Tags:

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.

like image 302
hatooku Avatar asked Sep 17 '16 19:09

hatooku


People also ask

Why do postmen work without CORS?

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!

Why is my CORS not working?

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.

How do I fix a CORS issue in REST API?

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.


1 Answers

You have to add CORS(app, resources={r"/*": {"origins": "*"}}) into your flask app.

Hope that solves the issue.

like image 58
porthunt Avatar answered Sep 28 '22 05:09

porthunt