Next.js Api 路由
API Routes 是一种使用 Next.js 创建 rest API 的方法。 Next.js 映射
/pages/api 文件夹中存在的任何文件,并将被视为 API 端点。 API 函数示例-
export default (req, res) => {
...
}
以下是一些需要考虑的要点。
req-req 是 http.IncomingMessage 的一个实例,用于从请求中获取数据。
res-res 是 http.ServerResponse 的一个实例,用于发送数据作为响应。
让我们创建一个示例来演示相同的内容。
在这个例子中,我们将在
pages/api 目录中创建一个 user.js。
让我们更新全球 CSS 支持章节中使用的 nextjs 项目。
在 pages/api 目录下创建 user.js 文件如下。
export default (req, res) => {
res.statusCode = 200
res.setHeader('Content-Type', 'application/json')
res.end(JSON.stringify({ name: 'Robert' }))
}
启动 Next.js 服务器
运行以下命令启动服务器-。
npm run dev
> nextjs@1.0.0 dev D:\Node\nextjs
> next
ready-started server on http://localhost:3000
info -Loaded env from D:\Node\nextjs\.env.local
event-compiled successfully
event-build page: /api/user
wait -compiling...
event-compiled successfully
event-build page: /next/dist/pages/_error
wait -compiling...
event-compiled successfully
验证输出
在浏览器中打开 localhost:3000/api/user,你会看到如下输出。