Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Access to XMLHttpRequest at '...' from origin 'localhost:3000' has been blocked by CORS policy

This may be a duplicate, but I havent found a thread relating specifically to my issue.

I am making the following API call:

const config = {   headers: {     "Access-Control-Allow-Origin": "*",     "Access-Control-Allow-Methods": "GET,PUT,POST,DELETE,PATCH,OPTIONS"   } };  const {   data: { ip } } = await axios.get("https://api.ipify.org?format=json", config); 

And this throws an error:

Access to XMLHttpRequest at 'https://api.ipify.org/?format=json' 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.

When I deploy my app to Heroku, the API call works as expected. However it does not work when developing on my local machine. Not sure what I'm missing here.

like image 839
Mike K Avatar asked Jul 12 '19 14:07

Mike K


People also ask

How do I fix a blocked CORS policy?

Use a Chrome extension to add Access-Control-Allow-Origin header into every response. To find one of them, just head over to Chrome Webstore and type in "CORS", dozens will show up in the search result. Or you can install CORS Helper, CORS Unblock or dyna CORS right away.

How do I resolve access to XMLHttpRequest?

In simple words, this error occurs when we try to access a domain/resource from another domain. To fix this, if you have access to the other domain, you will have to allow Access-Control-Allow-Origin in the server. This can be added in the headers. You can enable this for all the requests/domains or a specific domain.

What is CORS policy no Access-Control allow origin?

To allow any site to make CORS requests without using the * wildcard (for example, to enable credentials), your server must read the value of the request's Origin header and use that value to set Access-Control-Allow-Origin , and must also set a Vary: Origin header to indicate that some headers are being set ...


1 Answers

if you are building your rest api in nodejs. Follow the folowing simple steps

Stop the Node.js server.

npm install cors --save 

Add following lines to your server.js or index.js

var cors = require('cors')  app.use(cors()) // Use this after the variable declaration 

Now try to make your api call on the client side and it should work

like image 71
Boateng Ampomah Frederick Avatar answered Sep 20 '22 12:09

Boateng Ampomah Frederick