繁体   English   中英

如何在Node.js Express中使用多个请求处理功能?

[英]How to use multiple request handling functions with Node.js Express?

我需要在我的应用程序的大多数路由中执行重复的身份验证过程。 我决定给它一些结构,并在中间件功能中进行重复的工作。

如果身份验证过程无效,我应该做出响应并避免执行第二个函数,从而终止请求。

因此,代替:

app.route('/someRoute').all(function(request,response){});

我尝试了类似的东西:

app.route('/someRoute').all(repetitiveWork,secondMiddlewareFunction);

特别是这是我得到的虚拟示例:

app.route('/rutas').get(sum,test);


function sum (request,response,next) {

    if (5>1) {
        response.status(144).end('Fin');
        return next();
    }
};

function test (request,response,next) {
    response.send('Still alive');
};

但是,当我尝试对/rutas执行GET操作时,我什至没有得到响应。 我究竟做错了什么?

 At server side I can see the following when I try it: Error: Can't set headers after they are sent. 

您不能在结束响应后调用next(),而是要调用next(),以将请求/响应传递给堆栈中的下一个中间件。 考虑以下示例:

var app = require('express')();
app.route('/rutas').get(sum, test);
app.listen(function () { console.log(this.address()); });
var i = 0;

function sum (request, response, next) {
    i += 1;
    if (i % 2 === 0) {
        return response.status(200).end('Fin');
    }
    return next();
}

function test (request, response, next) {
    response.send('Still alive');
}

您需要在if语句之外调用next()如果您不希望它继续执行,还需要添加一个返回值以超出中间件的功能范围。 next()基本上是在说,不要停在此中间件上,而要转到下一个中​​间件。

app.route('/rutas').get(sum, test);

function sum (request, response, next) {
    if (5>1) {
        return response.status(144).end('Fin');
    }
    next();
};

function test (request, response) {
    response.send('Still alive');
};

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM