I m making GET request to Backend, with the token, but getting this error
Access to fetch at 'http://XXX.XX.XXX.XX:8067/v1/api/subscriber/list/1/20' from origin
'http://localhost:5173' has been blocked by CORS policy: Response to preflight request
doesn't pass access control check: It does not have HTTP ok status.
I have seen the solutions here but None of them worked me. Could you assist me with this issue?
Is this Frontend or Backend issue?
code:
export const getAllSubscribers = async (page, limit) => {
const token = localStorage.getItem('token').split(":")[1];
const url = api.allSubscribers(page, limit);
const headers = new Headers();
headers.append('Authorization', `Bearer ${token}`);
headers.append('Content-Type', 'application/json');
try {
const response = await fetch(url, {
method: 'GET',
headers: headers,
});
console.log("response------->", response.headers);
if (!response.ok) {
throw new Error(`Error fetching subscribers: ${response.statusText}`);
}
const data = await response.json();
return data;
} catch (error) {
console.error("Error occurred during allSubscribers request:", error);
throw error;
}
}
2
Answers
It’s a backend issue. Your server isn’t responding to the
OPTIONS
preflight HTTP call with a response with a success code, so the cross-origin call is disallowed. You probably just have the server responding toGET
, but certainGET
calls (and allPOST
and similar calls) trigger anOPTIONS
call before theGET
, a so-called "preflight" call, and your server is apparently not handling that (so it’s returning a404
or405
or similar instead, instead of a200
or similar containing a response with the necessary resource-sharing headers).More:
Preflight request an HTTP request of the OPTIONS method, sent before the request itself, in order to determine if it is safe to send it and this request is blocked due to CORS policy occurred when you tried to request to http://XXX.XX.XXX.XX:8067/ from http://localhost:5173.
If you are using Node.js + Express Backend, I recommend to configure CORS in the backend.
Also, you need to configure Fetch headers to accept credentials in Frontend as well.
Hope it will help you.
Thanks