gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-02 18:47:23 28 4
gpt4 key购买 nike

通过 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/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com