Search code examples
reactjsapache2axioscreate-react-app

Apache2 server applies Access-Control-Allow-Origin header to every response EXCEPT XHR


I’m testing deploying my CRA app using apache httpd. It’s consuming an external API, so I need to configure the Access-Control-Allow-Origin header to allow for this.

I’ve added a rule for adding an Access-Control-Allow-Origin header to the .htaccess file.

.htaccess:

Header always set Access-Control-Allow-Origin "*"

Options -MultiViews
RewriteEngine On
RewriteCond %{REQUEST_FILENAME} !-f
RewriteRule ^ index.html [QSA,L]

javascript http request:

Axios.get(URL).then(successCallback).catch(errorCallback);

The responses to the requests to the server on my localhost have the Access-Control-Allow-Origin set to the correct value; However, the one request it makes to an external API does not seem to have this header at all on the response given that Chrome shows this error:

Access to XMLHttpRequest at '{URL}’ from origin 'http://localhost:8080' 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.

I’ve checked that the headers and rewrite modules are enabled in the httpd.conf. I’ve been through all the various guides on enabling this functionality but haven’t had any success.


Solution

  • The responses to the requests to the server on my localhost have the Access-Control-Allow-Origin set to the correct value; However, the one request it makes to an external API does not seem to have this header at all on the response

    The server on your localhost and the external API are different servers.

    The configuration file for your local server won't affect the remote server.

    You need to configure that server to grant permissions with CORS.