【问题标题】:NextJS API error : "TypeError: res.status is not a function"NextJS API 错误:“TypeError:res.status 不是函数”
【发布时间】:2022-01-03 19:08:37
【问题描述】:

上下文

我正在使用NextJS v11.1.1-canary.11React v17.0.2Typescript v4.3.5

我想创建一个基于NextJS Typescript documentation 的简单API 端点,因此我在pages/proxy 文件夹中创建了一个名为login.tsx 的文件,其中包含非常简单的API 代码:

import type { NextApiRequest, NextApiResponse } from 'next'

export default function Login(req: NextApiRequest, res: NextApiResponse) {
  res.status(200).json({ name: 'John Doe' })
}

我的问题

当我尝试调用该 API 端点时,发生错误:

TypeError: res.status is not a function
    at Login (C:\wamp64\www\project-front\.next\server\pages\proxy\login.js:19:7)

完整的堆栈跟踪here

我进行了研究,在 Google 或 Stackoverflow 上找不到像我这样的案例,我是 NextJS 的新手,所以我可能误解了一些东西。有人知道我做错了什么吗?

【问题讨论】:

    标签: typescript api next.js typeerror


    【解决方案1】:

    您的示例运行良好。

    您可以通过将login.ts 文件放在pages/api/{whatever_you_want} 来解决此问题

    下一个文档:

    文件夹 pages/api 中的任何文件都映射到 /api/* 并且将被视为 API 端点而不是页面。它们只是服务器端的捆绑包,不会增加您的客户端捆绑包的大小。

    【讨论】:

      猜你喜欢
      • 2020-04-22
      • 2021-04-14
      • 2021-10-05
      • 2022-07-20
      • 2020-11-05
      • 2023-01-14
      • 2017-08-30
      • 2018-01-12
      • 1970-01-01
      相关资源
      最近更新 更多