首页 > 解决方案 > 仅对 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 请求时,我该如何做到这一点,以便我的中间件功能只执行?

标签: node.js

解决方案


对于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();
});

推荐阅读