NextJS calling await fetch POST inside api/.../route.tsx throws Error
Unanswered
Greenish Elaenia posted this in #help-forum
Greenish ElaeniaOP
I have a nextjs project with frontend code, and another separate project that has restful apis.
What is the best practice for calling this separate project? I currently have a await fetch inside route.tsx
client component:
const handleGoogleSignIn = async (token: string) => {
console.log("handleGoogleSignIn received token:" + token);
// Send google token to nextjs backend
try {
const response = await fetch('/api/login', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({
token: token,
host: window.location.host
}),
}).then(response => {
if (response.status == 200) {
console.log("/api/auth/login success");
// redirect to Lobby at /lobby
if (intervalID.current != undefined) {
clearInterval(intervalID.current);
}
router.push("/lobby");
}
});
} catch (error) {
console.error(error)
}
}
What is the best practice for calling this separate project? I currently have a await fetch inside route.tsx
client component:
const handleGoogleSignIn = async (token: string) => {
console.log("handleGoogleSignIn received token:" + token);
// Send google token to nextjs backend
try {
const response = await fetch('/api/login', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({
token: token,
host: window.location.host
}),
}).then(response => {
if (response.status == 200) {
console.log("/api/auth/login success");
// redirect to Lobby at /lobby
if (intervalID.current != undefined) {
clearInterval(intervalID.current);
}
router.push("/lobby");
}
});
} catch (error) {
console.error(error)
}
}
5 Replies
Greenish ElaeniaOP
app/api/login/route.tsx
export async function POST(request: Request) {
let status = 200;
let statusText = "OK";
// Get request body
const res = await request.json();
console.log(res)
const cookieStore = cookies();
cookieStore.set("showCheckboxes", generateCode(521))
// Call other backend
try {
const response = await fetch('https://something.com/2fa/google-signin', {
method: "POST",
body: JSON.stringify({
encryptedToken: res.token,
demo: "true",
host: res.host
})
});
if (!response.ok) {
throw new Error('Failed to fetch data'); // I'm seeing errors here
}
const data = await response.json();
console.log(data);
} catch (error) {
console.error(error); // I'm seeing errors here
}
return NextResponse.json(
{
some
},
{
status: status,
statusText: statusText,
}
);
}
export async function POST(request: Request) {
let status = 200;
let statusText = "OK";
// Get request body
const res = await request.json();
console.log(res)
const cookieStore = cookies();
cookieStore.set("showCheckboxes", generateCode(521))
// Call other backend
try {
const response = await fetch('https://something.com/2fa/google-signin', {
method: "POST",
body: JSON.stringify({
encryptedToken: res.token,
demo: "true",
host: res.host
})
});
if (!response.ok) {
throw new Error('Failed to fetch data'); // I'm seeing errors here
}
const data = await response.json();
console.log(data);
} catch (error) {
console.error(error); // I'm seeing errors here
}
return NextResponse.json(
{
some
ReturnedBodyThing: someReturnedBodyThing},
{
status: status,
statusText: statusText,
}
);
}
The error is not informative saying
"Error: Failed to fetch data
at POST (webpack-internal:///(rsc)/./app/api/login/route.tsx:33:19)"
"Error: Failed to fetch data
at POST (webpack-internal:///(rsc)/./app/api/login/route.tsx:33:19)"
Not sure how to proceed fixing this
Sun bear
You can try to fetch from a full url.
/api/login -> ${baseUrl}/api/loginGreenish ElaeniaOP
I figured out the body was missing a key and the url had a typo, otherwise this works:
nextjs frontend call nextjs api route, api route handler call separate project api.
nextjs frontend call nextjs api route, api route handler call separate project api.