nextjs fetch api call cors error
Unanswered
bscdev#1145 posted this in #help-forum
Hello Everyone, I am calling an external nodejs backend express api at nextjs client side throw fetch method. I am getting cors error
I checked when I run below fetch method via server actions then , fetch call the api successfully. I know server action does not use cors.
Even when I run below fetch method from nextjs client side without using the headers , if I pass token as a params like below removing headers then fetch called successfully.
nextjs frontend modified fetch
So my conclusion is when I use headers in the fetch method in client side, it gives cors error.
What went wrong in below original fetch. Please help.
nextjs frontend original fetch
I am ussing below headers at nodejs backend
I checked when I run below fetch method via server actions then , fetch call the api successfully. I know server action does not use cors.
Even when I run below fetch method from nextjs client side without using the headers , if I pass token as a params like below removing headers then fetch called successfully.
nextjs frontend modified fetch
const res= await fetch(backend-api/${token})So my conclusion is when I use headers in the fetch method in client side, it gives cors error.
What went wrong in below original fetch. Please help.
nextjs frontend original fetch
const res= await fetch("backend-api",{
headers:{
"Authorization":Bearer ${token}}
})
return res.json()I am ussing below headers at nodejs backend
res.setHeader('Access-Control-Allow-Origin', '*');
res.setHeader('Access-Control-Allow-Methods', 'OPTIONS, GET'); I used cors npm package functions also as a middleware at nodejs express backend.But nothing worked.2 Replies
app.use(
cors({
origin: "*",
preflightContinue: false,
})
);are you sure you installed correct package and update / restart servers ?
Also maybe share the error log's
@muadpn , Thanks for your reply and support. Yes There is no issue in backend. I can easily fetch the api from reactjs framework. Only I am facing issue in fetching an api with headers from the client side of nextjs framework (nextjs@14.1.4 ) .Without headers I could able to fetch. CORS error pops up once I mention headers object in the fetch method.Right now I removed headers, instead of passing the token via http header I compelled to pass the token as a http url param->
const res= await fetch(backend-api/${token}). I wrote the cors middleware as you advised but the result is same.