问题
When I try to access a JavaScript file hosted on Cloud Foundry using the Staticfile Buildpack, my browser refuses to load it and displays an error message in the console:
Access to script at ‘…’ from origin ‘…’ has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource
How do I configure cross-origin resource sharing (CORS) in the Cloud Foundry Staticfile Buildpack?
回答1:
To set up CORS with the Staticfile Buildpack:
Create a file named
Staticfilewith the following contents:root: public location_include: includes/*.conf%Ensure that the files you want your app to serve are located in the
publicfolder.Create the file
nginx/conf/includes/headers.conf(with its parent folders) with the following contents:add_header 'Access-Control-Allow-Origin' '*';
That's it! After your next cf push, the CORS header will be set.
For more clarity, see also the official code sample include_headers_public.
Explanation
As of the Staticfile Buildpack documentation:
If you create a file named
Staticfileand locate it in the build directory of your app, Cloud Foundry automatically uses the Staticfile buildpack when you push your app.
(It means you don't need to specify the staticfile_buildpack in your manifest.yml)
Then follow the instructions under Custom Location.
Custom Location allows you to specify custom location definitions with additional directives.
To customize the location block of the NGINX configuration file, follow the steps below.
Set an alternative
rootdirectory. Thelocation_includeproperty only works in conjunction with an alternativeroot.Create a file with location-scoped NGINX directives. See the following example, which causes visitors of your site to receive the
X-MySiteNameHTTP header:
- File:
nginx/conf/includes/custom_header.conf- Content:
add_header X-MySiteName BestSiteEver;Set the
location_includevariable in your Staticfile to the path of the file from the previous step. This path is relative tonginx/conf.Example:
root: public location_include: includes/*.conf
来源:https://stackoverflow.com/questions/58408784/how-to-configure-cors-policy-in-cloud-foundry-staticfile-buildpack-to-add-missin