api - 如何在 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 完全陌生。我可能只是错过了一些东西。
解决方案
要在 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
推荐阅读
- javascript - 将EventListener 添加到innerHTML
- javascript - 我在我的 html 页面上得到了这个 [object HTMLSpanElement]
- entity-framework - EF(在 WPF 中)第一次使用时不创建数据库(CreateDatabaseIfNotExists 不起作用)
- asp.net-core - Identity Server 4 没有为 `.well-known/openid-configuration` 设置`Access-Control-Allow-Origin`
- r - 配置 Travis CI 运行与 check --as-cran 完全相同的检查?
- reactjs - 在这种情况下,如何使用 useEffect 避免无限循环?(反应)
- erlang - 从二进制安装 Erlang 和 epmd 具有循环依赖关系
- android - 如何获取片段内在firebase中注册的用户数?
- kotlin - Kotlin 使用流函数或其他方法为变量赋值的捷径
- amazon-web-services - 为什么我在 CloudWatch 和 lambda 函数的控制台中看不到我的日志?