React has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header

3.7k Views Asked by At

According to this answers enable cors in .htaccess I would like to allow cross-origin requests from React application to the local server with Laravel application. So I added these lines at the beginning of my public/.htaccess. But it does not work.

Header add Access-Control-Allow-Origin "*"
Header add Access-Control-Allow-Headers "origin, x-requested-with, content-type"
Header add Access-Control-Allow-Methods "PUT, GET, POST, DELETE, OPTIONS"

The error says:

Access to XMLHttpRequest at 'http://localhost:8000/api/page/dynamic/111170/1' from origin 'http://localhost:3000' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource.

Can somebody tell me please what am I doing wrong?

1

There are 1 best solutions below

1
On

In your server you need to enable requests from the local host:3000 origin. By default most server frameworks will block requests that aren’t from its own ip. This is called a cross origin request policy and its to help secure your application.

You’ll need to change your servers CORS policy to include localhost:3000 - you’ll need to google how to do this for the specific server framework you’ve chosen.

To reiterate, this is not a problem with your React code but with your server.