How to configure CORS policy in Cloud Foundry Staticfile Buildpack to add missing 'Access-Control-Allow-Origin' header

喜你入骨 提交于 2020-06-17 04:31:09

问题


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:

  1. Create a file named Staticfile with the following contents:

    root: public
    location_include: includes/*.conf%    
    
  2. Ensure that the files you want your app to serve are located in the public folder.

  3. 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 Staticfile and 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.

  1. Set an alternative root directory. The location_include property only works in conjunction with an alternative root.

  2. Create a file with location-scoped NGINX directives. See the following example, which causes visitors of your site to receive the X-MySiteName HTTP header:

    • File: nginx/conf/includes/custom_header.conf
    • Content: add_header X-MySiteName BestSiteEver;
  3. Set the location_include variable in your Staticfile to the path of the file from the previous step. This path is relative to nginx/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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!