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粉1357999492024-03-29 18:24:48
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)); };