How to tackle CORS issues with ReactJS - reactjs

I have my backend running at a subdomain. Everything worked fine when my site ran on http protocol. But as soon as I moved the site to https my POST requests stopped working. Following was the error I got at my console.
Access to XMLHttpRequest at 'https://backend.example.com/api/handle-enquiry/' from origin 'https://example.com' has been blocked by CORS policy: Response to preflight request doesn't pass access control check: It does not have HTTP ok status.
My GET requests are working fine.
Note: I checked my network request headers using firefox's developer tools It shows 404 for preflight OPTIONS request.
I tried putting the following code into my .htaccess file
RewriteEngine On
RewriteCond %{REQUEST_METHOD} OPTIONS
RewriteRule ^(.*)$ $1 [R=200,L]
RESOLVED: But I am still confused about the solution. I just changed the way of configuring headers. Earlier I placed them in my index.php file of laravel backend. Now I am just configuring them at my .htaccess file. How does it make any difference? What am I missing?
Follows my updated .htaccess configuration
Header always set Access-Control-Allow-Origin "*"
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"
RewriteEngine On
RewriteCond %{REQUEST_METHOD} OPTIONS
RewriteRule ^(.*)$ $1 [R=200,L]

need to set it to always
Header always set Access-Control-Allow-Origin "*"
Header always set Access-Control-Allow-Methods "POST, GET, OPTIONS"
taken from: https://serverfault.com/questions/231766/returning-200-ok-in-apache-on-http-options-requests

Related

How can I refuse to serve index.html if the request comes with an incorrect Origin?

I'm developing a Chatbot with a React frontend, an Apache server and a load balancer on top of it. I added CORS configuration on Apache like so on the appropriate VirtualHost:
Require all granted
Header always set Access-Control-Allow-Origin "myURL"
Header always set Access-Control-Allow-Methods "POST,GET,PUT"
Header always set Access-Control-Max-Age "3600"
Header always set Access-Control-Allow-Headers "Authorization"
Header always set Access-Control-Expose-Headers "Authorization"
RewriteEngine On
RewriteCond %{REQUEST_METHOD} OPTIONS
RewriteRule ^(.*)$ $1 [R=200,L]
Whenever I make a request with a different Origin, I get the CORS headers, but it also returns 200 and the page contents. How can I make it so it returns a 401 and nothing on the body?
Is there anything I can do application-side? What about on Apache?
I'm aware of the security risks, but if someone ever needs to do this, it's actually quite simple.
You can use mod_rewrite or If..Else statements and add it to a .htaccess file or httpd.conf. Here's the solution with If..Else:
<If "%{HTTP:Origin} in { 'yourURL' }">
Require all granted
</If>
<ElseIf "%{HTTP:Origin} == ''">
Require all granted
</ElseIf>
<Else>
Require all denied
</Else>
I also allowed requests without Origin, but you can just remove the ElseIf otherwise.

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
Via npm start the second ACAO value is localhost:3000 but via npm build the second ACAO value is localhost so the second value appears to be dynamic and restricted to React
Adding a proxy value to package.json doesn't appear to help at all
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>

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.
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.

SLIM php Angularjs CORS

I'm using SLIM framework as backend and Angularjs as frontend.Normal GET and POST API's is working fine.Whenever i pass the headers in GET or POST method it is throwing 404 error.I used the .htaccess file for CORS.
RewriteEngine On
# Some hosts may require you to use the `RewriteBase` directive.
# If you need to use the `RewriteBase` directive, it should be the
# absolute physical path to the directory that contains this htaccess file.
#
# RewriteBase /
Header add Access-Control-Allow-Origin: "*"
Header add Access-Control-Allow-Headers: "origin, x-requested-with, content-type, authorization"
Header add Access-Control-Allow-Methods: "PUT, GET, POST, DELETE, OPTIONS"
RewriteCond %{REQUEST_FILENAME} !-f
RewriteRule ^(.*)$ index.php [QSA,L]
Please help me to fix this.
If you use Chrome, you can open the network tab within the Developer Tools to view the failed request. If it's related to CORS, then it will tell you why it failed.
A 404 error usually means that the endpoint cannot be found, so check carefully that the Angular code is requesting the URL that you think it should be.

CORS headers not working even after adding in .config file

I am working in AngularJs and making certain cross origin requests for accessing data and all stuff.
For the same,I added the required headers in the 000-default.config file of Apache Server to allow Cross Origin Requests but it isn't working.
It keeps returning the same error 'XMLHttpRequest cannot load 'domain-name'. No 'Access-Control-Origin' header present and blah blah..
I tried putting the headers inside the <IfModule mod_headers.c></IfModule> but still no difference in output.
I restarted the server too after every attempt. if thats what you are thinking :P
000-default.config file
<VirtualHost *:8081>
ServerAdmin webmaster#localhost
DocumentRoot /var/www/
Header set Access-Control-Allow-Origin "*"
Header set Access-Control-Allow-Methods "POST, GET, PUT, DELETE, OPTIONS"
Header set Access-Control-Allow-Headers "Origin, X-Requested-With, content-type, Accept"
Header set Access-Control-Allow-Credentials "true"
<IfModule mod_rewrite.c>
RewriteEngine On
RewriteBase /
RewriteCond %{REQUEST_METHOD} OPTIONS
RewriteRule ^(.*)$ $1 [R=200,L]
</IfModule>
<Directory />
Options FollowSymLinks
AllowOverride All
</Directory>
</VirtualHost>
After searching for answers i came across adding CORS chrome extension and disabling web security which made it work perfectly but what should I do for production purposes because no one would add extensions and disable security?
EDIT
The CORS problem is solved.I dont know how but it happened. I guess i restarted the system so it happened but still there is one issue left.
It works when we add --disable-web-security in chrome properties.This works fine in case of development. But how should i go about solving this for production purposes?
Please Help..

Resources