如何在 Next js api 中为 get 和 post 方法使用不同的中间件?

Lok*_*kar 2 api middleware http-method next.js

通过express,我们可以使用不同的中间件来处理get和post请求,例如。

// 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
})
Run Code Online (Sandbox Code Playgroud)

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

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

Iva*_* V. 6

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

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

或者您可以使用像next-connect这样的包,它支持像 API 一样的expressjs。在你的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
Run Code Online (Sandbox Code Playgroud)