Forums

js fetch error: blocked by CORS policy

Hi, I am trying to get the file list of mysite use javascript fetch

var url = api_base + "files/path/home/" + username + "/mysite/" 
fetch(url, {
headers: { 
  'Authorization': 'Token '+api_token
 },
method: 'GET', 
})
.then(response => {console.log(response)})

It gives me CORS error: Access to fetch at 'https://www.pythonanywhere.com/api/v0/user/shihm714/files/path/home/shihm714/mysite/' from origin 'null' has been blocked by CORS policy: Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource. If an opaque response serves your needs, set the request's mode to 'no-cors' to fetch the resource with CORS disabled.

If I run a similar request in Python, it works totally fine. What's the mistake in my js code and settings? Please help me, thank you!

The browser is blocking those requests because we do not provide CORS headers from our API, so it cannot be used from a browser. It would be a huge security issue if we allowed browsers to access the API.

Thank you for your reply! So I cannot use a flask app as a webpage backend?

Sure you can. As long as you set the CORS headers correctly in the Flask app.

I want to download a generated file from mysite files use web request, is that possible?

Sure. You'd just need to serve the file from your web app (most frameworks will have a way to serve a file) and make sure that the view that serves the file sets the CORS headers correctly.

I tried flask-cors but it dosen't work. Will you please give me an example of how to set it? Thank you so much!

The documentation for Flask-CORS is going to be much better at explaining what you need to do than I am.

I have the same issue. I have enabled password protection to my site under development with username and password in the pythonanywhere webApp. I am getting preflight CORS error during authorization. I am able to access the site if I disable the password. Looks like I cannot get around the CORS error as you don't support CORS from your API. Please confirm.

@krishvani Send us more details to support@pythonanywhere.com