A little late, but I remember that I ended up solving this issue by setting credentials: true
in my cors
config on my backend.
By complete accident, I noticed that if I set credentials: false
in my axios
client on the frontend, everything worked fine. However, switching it to true
kept throwing the error. I then put two and two together and set credentials: true
on my backend and everything worked as expected.
My app used cookies, so it had to be done this way.
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.
After many days finally I got a solution . Instead of using CORS simply like this
const cors = require('cors');
app.use(cors());
in your server index.js using CORS option will solve the issue and now you can pass cookies or other credentials
const cors = require('cors');
const corsOptions ={
origin:'http://localhost:3000',
credentials:true, //access-control-allow-credentials:true
optionSuccessStatus:200
}
app.use(cors(corsOptions));