Forums

Serving static files with CORS (Cross Origin Requests)

I am trying to access my static files hosted on python anywhere from a website hosted elsewhere, but I get the error:

Access to XMLHttpRequest at 'https://...pythonanywhere.com/...' from origin 'https://my_other_domain.com' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource.

The solution is to add headers to the response from the server, but I couldn't find such an option for static hosted files. My other option is to create a python webapp that serves the files and adds the headers, but I was wondering if there is a simpler way.

Thanks!

We don't have a UI for it, but if you're confident in using APIs, you can set up static headers for your website. This help page covers the API, and the one you need is the second from the bottom as of this posting. Let's say that the static files you wanted to make available over CORS were all under https://eranhirs.pythonanywhere.com/something/somethingelse -- you would POST to our API a request with the url key set to /something/somethingelse, the name key set to Access-Control-Allow-Origin, and the value key set to https://my_other_domain.com.

Perfect, thanks!

Putting it here in case anyone else needs it (replace your_username and your_token values). Note that putting * as the value is not recommended, more information about CORS can be found here.

import requests

import json

url = "https://www.pythonanywhere.com/api/v0/user/your_username/webapps/your_username.pythonanywhere.com/static_headers/"

payload = json.dumps({ "url": "/", "name": "Access-Control-Allow-Origin", "value": "*" })

headers = { 'Authorization': 'Token your_token', 'Content-Type': 'application/json' }

response = requests.request("POST", url, headers=headers, data=payload)

print(response.text)

Thanks for your example!