Next.js 13 DELETE request 'SyntaxError:意外结束JSON输入'

uqzxnwby  于 2023-10-18  发布在  其他
关注(0)|答案(3)|浏览(125)

我有一个使用Next 13的Web应用程序,api文件夹下有一个route.ts文件,目前包含2种不同的方法POSTPOST

这两种方法都成功接收到了请求,但是当尝试用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 })
    }
}
bmvo0sr5

bmvo0sr51#

这是一个已知的bug,已经得到解决(尽管没有太大的进展)

  • 你可以在这里阅读更多:https://github.com/vercel/next.js/issues/53882
  • 为了快速解决这个问题,我们只需要使用老式的方法(别名)。简而言之,目前可以很好地工作的两个是GET/POST。
  • 让您的钩子调用REST API
export async function fetchRemoveWorkPlaces(ids: string[]) {
    const data = { ids: ids }
    const response = await fetch(
        '/api/workPlace2',  // Change it to something similar
        {
            method: 'DELETE',
            headers: {'Content-Type': 'application/json'},
            body: JSON.stringify(data)
        }
    )
  }

然后在新获取的“POST”请求中插入删除代码

export async function POST(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 })
    }
}
zi8p0yeb

zi8p0yeb2#

在你的NextJs前端:

await axios.delete(`/api/item`, { params: { id } })

在NextJs后端:/API/item/route.ts

export async function DELETE(req: Request) {
  console.log("DELETE", req, req.url);
  const id = req.url.split('=')[1];
  ...
}
kmynzznz

kmynzznz3#

DELETE请求通常不包含body,所以你可以在查询参数中发送ID,而不是在前端:

export async function fetchRemoveWorkPlaces(ids: string[]) {
    const response = await fetch(
        `/api/workPlace?ids=${JSON.stringify(ids)}`, 
        {
            method: 'DELETE',
            headers: {'Content-Type': 'application/json'},
        }
    );
}

在服务器端,读取查询参数,而不是尝试解析主体:

export async function DELETE(req: Request, res: NextResponse , context: {}) {

    try {
        const ids: string[] = JSON.parse(req.query.ids as string); // Parse the query parameter

        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 });
    }
}

相关问题