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

标签 api next.js middleware http-method

通过 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
})

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

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

最佳答案

要在 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

关于api - 如何在 Next js api 中对 get 和 post 方法使用不同的中间件?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/67255067/

相关文章:

javascript - 错误: `experimental.runtime` requires `experimental.reactRoot` to be enabled along with React 18

Laravel 中间件 403

node.js - 无法从node.js中的中间件获取 session 数据

javascript - componentDidMount 多次获取调用最佳实践?

java - 如何查看来自API的信息? http://178.62.246.236/Author/GetBooksByAuthor

java - 使用不同的查询参数 JOIN 不同的方法 : REST

reactjs - 如何在 NextJS Image 组件中运行图像的 onLoad 函数

ruby-on-rails - 我们可以使用什么方法来干净地为 Rails 应用程序中的 API 客户端和普通用户提供访问权限?

reactjs - useState set 方法没有立即反射(reflect)变化(Stackoverflow 中建议的解决方案不起作用)

java - MQ 队列与批处理 : how to replay asynchronous process when it fails