node.js - 仅对 GET 请求使用 express 中间件
问题描述
我理解它的方式,如果我这样做:
app.use('/something', function(req, res, next) {
// some content here
});
这基本上意味着如果有对“某事”的请求,则中间件(我的函数)在下一个函数之前执行。
所以如果我有这样的东西来处理 GET 请求,
app.get('/something', function(req, res, next) {
console.log('hello');
});
然后在我的原始函数执行完成后将打印出'hello'。
但是,当我只发出 GET 请求而不是 POST 请求时,我该如何做到这一点,以便我的中间件功能只执行?
解决方案
对于GET
唯一的中间件,只需执行以下操作
// Get middleware
app.get('/something', function(req, res, next) {
console.log('get hello middleware');
next();
});
// GET request handler
app.get('/something', function(req, res) {
console.log('get hello');
res.end();
});
// POST request handler
app.post('/something', function(req, res) {
console.log('post hello');
res.end();
});
推荐阅读
- php - 如何将实体与 DBAL sqlsrv 一起用于 easybundle 管理员
- python - 如何根据年份在 Pandas 数据框中创建多个列
- jenkins - Jenkins中“与{node}相关的项目”是什么意思?
- c# - DateTime.Parse 在 Windows Server 2012 上不起作用
- python - 带路径的 Python OPC-UA 访问节点
- python - 摆脱 Pandas 列中字符串中的特定字符
- c - 用于 simd 的 pragma omp 不会在 GCC 中生成向量指令
- c++ - C++ 从列表中读取文本时只读取最后一行
- performance - 如何解决“Microsoft.AspNetCore.Server.Kestrel.Core.BadHttpRequestException:由于数据到达太慢导致读取请求正文超时”?
- javascript - 允许用户将反应网页导出为 pdf