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.