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