仅将快速中间件用于GET请求

时间:2018-06-25 02:45:45

标签: node.js

我的理解方式,如果我做类似的事情:

app.use('/something', function(req, res, next) { // some content here });

这基本上意味着,如果请求“某事”,则在下一个功能之前执行中间件(我的功能)。

因此,如果我有这样的事情来处理GET请求,

app.get('/something', function(req, res, next) { console.log('hello'); });

然后,当我的原始功能执行完毕后,“ hello”将被打印出来。

但是如何做到这一点,以便仅当我发出GET请求而不是POST请求时才执行中间件功能?

2 个答案:

答案 0 :(得分:1)

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

答案 1 :(得分:0)

app.post('/something', your_middleware, function(req, res, next) {
   console.log('hello');
});

仅在发布请求期间,将执行your_middleware。

your_middleware应该是如下功能:

function(req, res, next){
    ....
    next()
}

您可以通过这种方式针对特定的路由和请求类型插入所需的尽可能多的中间件