gpt4 book ai didi

Postman: SyntaxError: Unexpected number in JSON at position 1 at JSON.parse(POSTMAN:语法错误:JSON中JSON中位置1处的意外数字。parse)

转载 作者:bug小助手 更新时间:2023-10-28 10:33:20 27 4
gpt4 key购买 nike



I am a beginner at web development and I am trying to use Postman to send a POST request to one of my application's APIs.
I am using the Next.JS framework to build my website.

我是Web开发的初学者,我正在尝试使用Postman向我的应用程序的一个API发送POST请求。我正在使用Next.JS框架来构建我的网站。


Here is my API:

以下是我的接口:


import type { NextApiRequest, NextApiResponse } from "next"

export default async (
req: NextApiRequest,
res: NextApiResponse,
) => {

const userData = JSON.parse(req.body)
res.status(200).json(userData)
}

I simplified my API until I caught the error, and I believe that it is related to the JSON.parse(req.body) line.

我简化了我的API,直到我发现了错误,我相信它与JSON.parse(req.body)行有关。


This is a print of the data that I used to test the API on Postman

这是我用来在Postman上测试API的数据的打印


I get the following error:

我得到以下错误:


SyntaxError: Unexpected number in JSON at position 1
at JSON.parse (\u003canonymous\u003e)
at __WEBPACK_DEFAULT_EXPORT__ (webpack-internal:///(api)/./pages/api/login.ts:9:27)

Previously, I used this API to authenticate users, and everything worked fine, except when I tried to insert data into the body of a Postman POST request.

以前,我使用此API对用户进行身份验证,除了尝试将数据插入到邮递员POST请求的正文中之外,一切都运行得很好。


Can someone help me? I have no idea what to do.

有人能帮我吗?我不知道该怎么办。


更多回答

You're sending the POST data in multipart/form-data format, you can't simply handle it with JSON.parse. Try sending the body as a JSON string instead.

您正在以多部分/表单数据格式发送POST数据,不能简单地使用JSON.parse来处理它。请尝试将正文作为JSON字符串发送。

优秀答案推荐

I was having the same issue adding FormData via Router Handler (App Router)

我在通过路由器处理程序(应用程序路由器)添加FormData时遇到了相同的问题


If you are having simliar issue be aware with a NextRequest object you canl call req.formData() to return form data, no need parsing.

如果您遇到类似问题,请注意NextRequest对象,您可以调用req.formData()来返回表单数据,无需解析。


Also sending a multipart/form-data header is not needed using this method.

此外,使用此方法不需要发送多部分/表单数据报头。



If you want to deserialize the body from a POST request, you also have to send a request where the body contains any data because otherwise, req.body will be null and that is not valid json.

如果你想从POST请求中解析body,你还必须发送一个请求,其中body包含任何数据,因为否则,req.body将为null,这不是有效的json。


更多回答

Thanks for this answer, I don't understand why they don't talk about this in nextjs documentation, if they do I totally missed it

谢谢你的回答,我不明白为什么他们不在Nextjs文档中讨论这个,如果他们这样做了,我完全听不懂

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com