我有一个使用Next 13的Web应用程序,api
文件夹下有一个route.ts
文件,目前包含2种不同的方法POST和POST。
这两种方法都成功接收到了请求,但是当尝试用JSON解析请求的主体时,它只对POST有效,而对POST无效,尽管我执行的是完全相同的步骤。
我在开发工具的“网络”选项卡中检查了请求,有效负载很好。我错过了什么?
这就是错误:
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)
DELETE请求主体应该包含一个json,该json具有一个属性-字符串数组。前端如下:
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)
}
)
}
这是服务器中的route.ts
:
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 })
}
}
3条答案
按热度按时间bmvo0sr51#
这是一个已知的bug,已经得到解决(尽管没有太大的进展)
然后在新获取的“POST”请求中插入删除代码
zi8p0yeb2#
在你的NextJs前端:
在NextJs后端:/API/item/route.ts
kmynzznz3#
DELETE请求通常不包含body,所以你可以在查询参数中发送ID,而不是在前端:
在服务器端,读取查询参数,而不是尝试解析主体: