Next.js 13 DELETE请求JSON解析报错:Unexpected end of JSON input
问题描述
我开发了一个基于Next.js 13的Web应用,api目录下的route.ts文件包含POST和DELETE两种请求方法。两种请求都能成功接收,但解析请求体时POST正常,DELETE却报错,尽管操作步骤完全一致。我在开发者工具的Network面板中确认请求Payload正常,报错信息如下:
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,前端代码:
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 }) } }
解决方案
1. 修正路由函数参数错误
Next.js 13 App Router的路由处理函数(POST/DELETE等)参数格式为(req: Request, context: { params?: ... }),你错误地将NextResponse作为第二个参数传入,虽未影响POST请求,但可能干扰DELETE请求的请求体解析逻辑。修正后的函数参数如下:
// 修正POST函数 export async function POST(req: Request, context: {}) { // 原逻辑保持不变 } // 修正DELETE函数 export async function DELETE(req: Request, context: {}) { // 原逻辑保持不变 }
2. 手动读取并解析请求体(备选方案)
若修正参数后问题仍存在,可能是Next.js底层undici库对DELETE请求体的处理存在兼容问题,可尝试手动读取文本后解析JSON替代req.json():
export async function DELETE(req: Request, context: {}) { try { const bodyText = await req.text(); const body = bodyText ? JSON.parse(bodyText) : {}; 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. 改用查询参数传递数据(推荐兼容方案)
尽管HTTP规范允许DELETE请求带请求体,但部分服务器、代理或CDN可能会忽略该请求体。更兼容的做法是将ids放到URL查询参数中:
前端代码修改:
export async function fetchRemoveWorkPlaces(ids: string[]) { const searchParams = new URLSearchParams(); ids.forEach(id => searchParams.append('ids', id)); const response = await fetch( `/api/workPlace?${searchParams.toString()}`, { method: 'DELETE' } ); }
服务端代码修改:
export async function DELETE(req: Request, context: {}) { try { const ids = req.url.searchParams.getAll('ids'); const response = await workPlaceDao.deleteWorkPlace(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 }); } }
内容的提问来源于stack exchange,提问作者IdoBa
相关产品推荐
相关产品推荐

