'身体的论点'在Next.js&#x27的API中未提供Send()\ JSON()
我在Next.js中使用API路线。在“ API”文件夹中,我的'file.tsx'包含以下内容:
import type { NextApiRequest, NextApiResponse } from "next";
const someFunction = (req: NextApiRequest, res: NextApiResponse<data>) => { the rest of the code... }
一切都起作用。但是,关于以下行:
res.status(200).send();
send()
突出显示,我会收到以下typescript错误:
期望有1个参数,但有0.TS(2554)Utils.d.ts(182,25): 没有提供“身体”的论点。
跟随文档( https://nextjs.org/docs/api-routes/response-routes/response-routes/response-routes/response-routes/response-routes-帮助者),我尝试添加一个参数,例如res.status(200).send({key:“ value”})
或res.status(200)。 (“字符串”)
或两者都带有json()
而不是send()
。
我什至复制了文档中的确切示例,但此错误仍然存在。 清除错误(作为测试)的唯一一件事是更改键入 - 但自然,这是不希望的,因为错误可能是有原因的。
我在这里错过了什么吗?
I'm using an API route in Next.js. In the 'api' folder, my 'file.tsx' contain the following:
import type { NextApiRequest, NextApiResponse } from "next";
const someFunction = (req: NextApiRequest, res: NextApiResponse<data>) => { the rest of the code... }
Everything does work. But, regarding the following line:
res.status(200).send();
send()
is highlighted and I get the following TypeScript error:
Expected 1 arguments, but got 0.ts(2554) utils.d.ts(182, 25): An
argument for 'body' was not provided.
Following the docs (https://nextjs.org/docs/api-routes/response-helpers), I tried adding an argument like res.status(200).send({key: "value"})
, or res.status(200).send("string")
or both with json()
instead of send()
.
I even copied the exact examples from the docs, but still this error persist.
The only thing that cleared the error (as a test) was changing the typing - but naturally, this is undesirable, as the error is probably there for a reason.
Am I missing something here?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
这里有几件事。对于第一个错误,打字稿抱怨没有提供“身体”的论点。众所周知,此错误非常简单。另一个错误来自已经为您定义的响应类型:
其中
data
类型定义为:它是具有类型
string 。
因此,如果您想发送一个普通的字符串,那么您需要对此进行修改:
您还可以在响应中直接定义它,例如:
无论如何,您需要牢记打字稿需要您要明确您发送哪种类型的数据作为响应。在项目中使用打字稿的重点是通过将类型的安全检查添加到代码中来防止错误。
参见日常类型以了解更多。
There are a couple of things going on here. For the first error, Typescript is complaining that no argument for 'body' was provided. This error is pretty straightforward as you already know. The other error comes from the type of response that is already defined for you:
Where the
Data
type is defined as:Which is a an object with a name property that is of type
string
.So, if you want to send a plain string then, you'll need to modify the type to this:
You could also define it directly in the response, like this:
In any case, you need to keep in mind that Typescript requires you to be explicit of what type of data you're sending as a response. The whole point of having Typescript in a project is to prevent errors by adding type safety checks to the code.
See Everyday Types to learn more.