教程 > next.js 中文教程 > 阅读:1538

next.js api 中间件 middlewares——迹忆客-ag捕鱼王app官网

next.js 为api 路由提供了内置的中间件,用于解析传入的请求 (req)。这些中间件是:

  • req.cookies - 包含请求发送的 cookie 的对象。 默认为 {}
  • req.query - 包含查询字符串的对象。 默认为 {}
  • req.body - 包含由 content-type 解析的正文的对象,如果没有发送正文,则为 null

让我们创建一个示例来看一下中间件是如何使用的。

在此示例中,我们将更新 pages/api 目录中的 user.js。

让我们更新 api routes 章节中使用的 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 /workspace/node/nextjs
> next dev
ready - started server on 0.0.0.0:3000, url: http://localhost:3000
event - compiled client and server successfully in 495 ms (124 modules)

在浏览器中打开 localhost:3000/api/user?counter=1 ,我们将看到以下输出。

nextjs api 中间件 middlewares

查看笔记

扫码一下
查看教程更方便
网站地图