I have configured my code in this manner on my express backend and have the cors library installed.
I am however getting this error:
Access to fetch at 'mybackend.com' from origin 'domain1.com' has been blocked by CORS policy: 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.
How can I solve this?
My backend and frontend code are as below respectively
const allowedDomains = [
'domain 1',
'domain 2',
];
app.use(cors(
{
origin: function (origin, callback) {
if (allowedDomains.indexOf(origin) != -1) {
callback(null, true);
} else {
callback(new Error(`Access has been blocked `));
}
},
credentials: true,
}
));
await fetch(`mybackend.com' ,{
method:'GET',
headers: new Headers({
'Content-Type':'application/json',
'Authorization':`Bearer ${token}`,
}),
body:null,
})
As per my limited understanding of Fetch API and CORS, I think you have to add mode: 'cors' as well as the header Access-Control-Allow-Origin: '*' or Access-Control-Allow-Origin: 'mybackend.com'. After doing that, your await fetch(...) block would look something like this.
fetch(URL, {
mode: 'cors',
method:'GET',
headers: {
'Access-Control-Allow-Origin':'*',
'Content-Type':'application/json',
'Authorization':`Bearer ${token}`,
},
body:null,
})
.then(response => response.json())
.then(data => { ... });
Hope this helps!