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.
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.
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.
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 ...
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With