Jacksonkr
Jacksonkr

Reputation: 32247

ReactJS cors "The 'Access-Control-Allow-Origin' header contains multiple values"

Scenario

I am using fetch to gather json from my remote apache server. In the beginning I was receiving the following CORS violation:

Access to fetch at 'http://dev.mediajackagency.com/clients/dawna/row/wordpress/wp-content/uploads/2019/01/bw.jpg' from origin 'http://localhost:3000' 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. If an opaque response serves your needs, set the request's mode to 'no-cors' to fetch the resource with CORS disabled.

I overcame this issue by enabling CORS in the server's .htaccess file for this project

Header always set Access-Control-Allow-Origin "*"
Header always set Access-Control-Allow-Credentials "true"
Header always set Access-Control-Allow-Methods "POST, GET, OPTIONS, DELETE, PUT"
Header always set Access-Control-Max-Age "1000"
Header always set Access-Control-Allow-Headers "x-requested-with, Content-Type, origin, authorization, accept, client-security-token"

Now I'm getting a different CORS violation of

Access to fetch at 'http://some.domain/some/endpoint' from origin 'http://localhost:3000' has been blocked by CORS policy: Response to preflight request doesn't pass access control check: The 'Access-Control-Allow-Origin' header contains multiple values '*, http://localhost:3000', but only one is allowed. Have the server send the header with a valid value, or, if an opaque response serves your needs, set the request's mode to 'no-cors' to fetch the resource with CORS disabled.

Question

How can I find where the Access-Control-Allow-Origin is getting set for localhost:3000 ? I've done a full index and search for strings related to cors, headers, etc etc with no luck. All ideas are appreciated.

Extra

Upvotes: 0

Views: 5202

Answers (1)

Jacksonkr
Jacksonkr

Reputation: 32247

I ultimately could not decide if CRA's dev node server was creating this issue (by adding 'localhost:3000' as an allowed origin) or if I'm just not as good with .htaccess files as I thought. Regardless here is what finally ended up working:

API server's .htaccess

# allows image files to bypass cors @jkr
<Files *.jpg>
  Header always set Access-Control-Allow-Origin "*"
  Header always set Access-Control-Allow-Credentials "true"
  Header always set Access-Control-Allow-Methods "POST, GET, OPTIONS, DELETE, PUT"
  Header always set Access-Control-Max-Age "1000"
  Header always set Access-Control-Allow-Headers "x-requested-with, Content-Type, origin, authorization, accept, client-security-token"
</Files>

#always allow preflight to pass @jkr
<LimitExcept OPTIONS>
  RewriteEngine On
  RewriteCond %{REQUEST_METHOD} OPTIONS
  RewriteRule ^(.*)$ $1 [R=200,L]
</LimitExcept>

Upvotes: 1

Related Questions