Forums

Set access control header for static content?

I would like to set the following header to allow external access to some static content (xml files on my web): Access-Control-Allow-Origin: *

I'm generating some static content I am trying to load in on another domain and getting XMLHTTPRequest errors: XMLHttpRequest cannot load https://mysite.com/myfile.xml. No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://othersite.com/script.js' is therefore not allowed access.

There's no way to add headers to the static files served at the moment, but that's a great idea for a feature and I have raised a ticket for it.

In the meantime, you can make a small Flask web app that uses send_from_directory and this decorator to serve the file for you.

@glenn was this ever done? I'd like it too.

No it's not possible to set headers for static contents yet. (but glenn's solution above works to add the header)

Thanks, Conrad, I've tried from flask.ext.cors import cross_origin and from flask_cors import cross_origin and apparently those don't work?

I don't know the package, but you probably need to do more than just import it.

No problem, I created and set the source of a blank img element with parameters at the end of the URL which gave me the same upload of the data I need without CORS nonsense.

Hi, it's 3 years since this was first requested and a year since last revisited. Setting correct CORS headers is a must to get any Vue/React/Angular/etc site to communicate with its API. Please raise the priority on this issue so we can get our static files served to clients. Even Flask's documentation for the "send_from_directory" function you link to above recommends serving static files outside of Flask. Thanks!

This is not really a high priority for us, since there's such an easy workaround. Also, since CORS is a dynamic header (unless you use '*', which seems like a worse idea than serving a few files through your web app), it does actually require that some code must be run to determine if the source domain is permitted.

Static files CORS headers are not necessary for any Vue/React/Angular/etc site to communicate with its API. In general, you would serve the static part of the site on the same domain as the API, so that CORS is not required. If the API is on a different domain to the page where the call is being made, then the API endpoints are going to be code that performs the API action and probably not static files.