首页 > 解决方案 > 如何在 Next js api 中使用不同的中间件来获取和发布方法?

问题描述

使用 express 我们可以使用不同的中间件来获取和发布请求,例如。

// GET method route
app.get('/users', function (req, res) {
    // handle get request
})
    
// POST method route
app.post('/users', auth, function (req, res) {
    // handle post request
})

我如何在下一个 js 中做同样的事情。

我对下一个 js 完全陌生。我可能只是错过了一些东西。

标签: apinext.jsmiddlewarehttp-method

解决方案


要在 API 路由中处理不同的 HTTP 方法,您可以req.method在请求处理程序中使用。

export default function handler(req, res) {
  if (req.method === 'POST') {
    // Process a POST request
  } else {
    // Handle any other HTTP method
  }
}

或者你可以使用像next-connect这样的包来启用 expressjs 之类的 API。在您的api文件中:

import nc from "next-connect";

const handler = nc()
  .use(someMiddleware())
  .get((req, res) => {
    res.send("Hello world");
  })
  .post((req, res) => {
    res.json({ hello: "world" });
  })
  .put(async (req, res) => {
    res.end("async/await is also supported!");
  })
  .patch(async (req, res) => {
    throw new Error("Throws me around! Error can be caught and handled.");
  });
export default handler

推荐阅读