NextJS beta application router: request using fetch fails but works fine in browser
P粉141035089
P粉141035089 2024-03-28 21:44:56
0
1
373

I'm using nextJS with the APP directory and I'm having this issue when doing a GET request...

I have the following function to get Projects from my /project Route.ts.

Looks like it's not triggering the GET function in my routes.ts

console.log("in GET /projects") never fires and I get an unexpected JSON error at the end.

However, if I access "http://localhost:3000/api/project" in the browser, it does hit the GET function in my routes.ts and I get back JSON...

Thanks for your help, I've been working on this problem for a while...

export const projectsGet = async () => {
  const res = await fetch("http://localhost:3000/api/project", {
    method: "GET",
    headers: {
      "Content-Type": "application/json",
    },
  });

  console.log(res, 'before')     //triggers
  const data = await res.json()  // error: Unexpected end of JSON input
  console.log(data, 'after')     // does not trigger
  
  return data
};

This is my project route, located in /api/project/route.ts. I have a POST route in the same file which creates a project and works fine...

export const GET = async () => {
  console.log("in GET /projects");  //never triggers unless i visit the URL in browser

  const user = await getUserFromCookie(cookies());

  const projects = await db.project.findMany({
    where: {
      ownerId: user?.id,
    },
    include: {
      tasks: true,
    },
  });

  const filteredProjects = projects.filter((project) => {
    return project.deleted === false;
  });

  return NextResponse.json(filteredProjects);
};

P粉141035089
P粉141035089

reply all(1)
P粉135799949

I think you should return json in this form in `/api/project/route.ts.

export async function GET(){
  console.log("in GET /projects");

  const user = await getUserFromCookie(cookies());

  const projects = await db.project.findMany({
    where: {
      ownerId: user?.id,
    },
    include: {
      tasks: true,
    },
  });

  const filteredProjects = projects.filter((project) => {
    return project.deleted === false;
  });

  return new Response(JSON.stringify(filteredProjects));
};
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template