I am currently working on a web app using Next 13 and I have a route.ts
file located in the api
folder. This file contains two different methods, POST and DELETE.
While both methods successfully receive the request, I am facing an issue with JSON parsing the body of the DELETE request. Strangely, it works for the POST method but not for the DELETE method, even though I am following the same steps.
I have checked the request in the 'Network' tab of the developer tools and the payload seems to be fine. Can anyone help me figure out what I might be missing?
Here is the Error message I am encountering:
SyntaxError: Unexpected end of JSON input
at JSON.parse (<anonymous>)
at NextRequest.json (node:internal/deps/undici/undici:6160:23)
at process.processTicksAndRejections (node:internal/process/task_queues:95:5)
at async DELETE (webpack-internal:///(sc_server)/./app/api/workPlace/route.ts:35:22)
at async eval (webpack-internal:///(sc_server)/./node_modules/next/dist/server/future/route-modules/app-route/module.js:242:37)
The JSON structure of the DELETE request body should consist of an array of strings.
This is how the frontend code looks like:
export async function fetchRemoveWorkPlaces(ids: string[]) {
const data = { ids: ids }
const response = await fetch(
'/api/workPlace',
{
method: 'DELETE',
headers: {'Content-Type': 'application/json'},
body: JSON.stringify(data)
}
)
}
Below is the implementation of the route.ts
on the server side:
export async function POST(req: Request, res: NextResponse , context: {}) {
try {
const body: any = await req.json()
const response = await workPlaceDao.addWorkPlace(body)
return NextResponse.json(
{
success: true,
workPlace: response
},
{ status: 200 })
} catch (e) {
console.log('Error occurred while Add Work Place Request');
console.log(e);
return NextResponse.json({success: false}, { status: 500 })
}
}
export async function DELETE(req: Request, res: NextResponse , context: {}) {
try {
const body: any = await req.json()
const response = await workPlaceDao.deleteWorkPlace(body.ids)
return NextResponse.json(
{
success: true,
},
{ status: 200 })
} catch (e) {
console.log('Error occurred trying to delete Work Places');
console.log(e);
return NextResponse.json({success: false}, { status: 500 })
}
}