NextJS教程

Next.js API 中间件

Next.JS 中的 API 路由具有内置的中间件,可帮助解析传入的请求。
以下是中间件
req.cookies-cookies 对象包含请求发送的 cookie。默认值为 {}。 req.query-查询对象包含查询字符串。默认值为 {}。 req.body-查询对象包含使用"内容类型"解析的请求正文。默认值为空。
让我们创建一个示例来演示相同的内容。
在此示例中,我们将更新 pages/api 目录中的 user.js。
让我们更新API路由章节中使用的nextjs项目。
在 pages/api 目录下创建 user.js 文件如下。
export default (req, res) => {
   res.statusCode = 200
   res.setHeader('Content-Type', 'application/json')
   res.end(JSON.stringify({ query: req.query }))
}

启动 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

验证输出

在浏览器中打开 http://localhost:3000/api/user?counter=1,您将看到以下输出。
{"query":{"counter":"1"}}
昵称: 邮箱:
Copyright © 2022 立地货 All Rights Reserved.
备案号:京ICP备14037608号-4