Forums

Flask CORS is not solving CORS issue

I've installed Flask CORS on my pythonanywhere account per flask-cors.readthedocs.io using

pips3.6 install --user flask-cors

I've loaded it in my app using:

from flask_cors import CORS
app = Flask(__name__)
CORS(app)

But nothing! When I load the page, I still get CORS errors. There is no indication in the pythonanywhere that any of the modules are missing or anything.

Reading the documentation for flask-cors I got the impression that once up and running, any CORS errors should be resolved for all pages in the site.

How can I get this to work?

probably app = CORS(app)

Changing it to app = CORS(app) makes the app fail. It goes from serving the data to throwing this error:

Error code: Unhandled Exception

I think Conrad was mistaken in his suggestion. Could you give an example of a page on your site that is generating the CORS errors so that we can take a look?

I have resolved the issue. The issue was that I was loading CORS but I also was setting the headers in the cross-origin headers in JSON object. Removed that and now it works!

Ah, excellent -- glad you worked it out!

Can you post the code for the solution? Im running into same issue. Thanks.

Can you post the code for the solution? Im running into same issue. Thanks.

This solved it for me:

from flask_cors import CORS   
app = Flask(__name__)
CORS(app)

And on the other side (react):

fetch("https://username.pythonanywhere.com/app", { method: 'get', mode: 'cors' }

Thanks!

Thanks! Can anyone teach me how to install flask_cors on pythonanywhere? Im new in the site. I tried from console but keep getting errors. Which would be the right sintaxis for that?

See http://help.pythonanywhere.com/pages/InstallingNewModules/

I was having a very similar problem. I could make GET requests but not POST. The problem persisted after installing FLASK-CORS. The solution was in the javascript code on the client side.

When you see this error, it means your code is triggering your browser to send a CORS preflight OPTIONS request, and the server’s responding with a 3xx redirect. To avoid the error, your request needs to get a 2xx success response instead.

https://stackoverflow.com/a/42172732

That's useful, thanks for sharing! So in general, POST views should not return redirect responses for cases like this.

I know this is old...But I had a very similar issue and this helped me solve it but it wasn't obvious right away so hopefully I can save someone some headache.

My issue was that I was using "myapp.com" instead of "www.myapp.com" in my request. I have a permanent redirect setup for "myapp.com". that was causing the 3xx redirect code Robotrodeo mentioned which caused the preflight to fail. Just make sure to use your actual address if you have a redirect setup like I do.

Thanks Robotrodeo! Your comment made me realize this is what was happening.