I have a nextjs application and when I execute a call to fetch a page from an external website if I do it from the backend via an API route everything works fine however when I do it from the frontend side I get a cors error.
This is the code from the API route:
async function getPage(url: string) {
const response = await fetch(url);
// do stuff
}
export async function POST(req: any) {
const request = await req.json();
try {
await getPage(request.url);
return NextResponse.json({ status: 200 });
} catch (err: any) {
console.log(err);
return NextResponse.json({}, { status: 400, statusText: 'The website does not exist or is currently down.' });
}
}
This is the same code in the frontend that is throwing an error:
async function getPage(url: string) {
const response = await fetch(url, {
mode: 'cors',
headers: {
'Access-Control-Allow-Origin': '*',
}
});
// do stuff
}
const fetchPageFromSite = async () => {
await getPage(url);
}
I am using the fetchPageFromSite inside a useEffect.
3
Answers
This should help you CORS error with jquery. By the way almost always this error fixes from the server side
The concept of
CORS
– Cross Origin Resource Sharing – is applicable only on the client side. When you are sending request from the server (api
route), theurl
you are fetching from doesn’t know about the origin or domain of your website. Thus, your call fromapi
route works without any errors.CORS must be manage from Back-End (the external website you want to fetch).
Because Back-end of that website need to allow Cross Origin to your page or all (*).
You can find more details about CORS here https://developer.mozilla.org/en-US/docs/Web/HTTP/CORS