简体   繁体   English

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

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

I need to do a repetitive auth process in most routes in my app. 我需要在我的应用程序的大多数路由中执行重复的身份验证过程。 I decided to give some structure to it and get that repetitive work in a middleware function. 我决定给它一些结构,并在中间件功能中进行重复的工作。

If the auth process isn't valid, I should response and avoid second function to execute, terminating the request. 如果身份验证过程无效,我应该做出响应并避免执行第二个函数,从而终止请求。

So, instead of: 因此,代替:

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

I tried something like: 我尝试了类似的东西:

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

In particular this is the dummy example I got: 特别是这是我得到的虚拟示例:

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');
};

However, when I try to do a GET to /rutas I'm not even getting a response. 但是,当我尝试对/rutas执行GET操作时,我什至没有得到响应。 What am I doing wrong? 我究竟做错了什么?

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

You can't call next() after ending a response, next() is meant to be called to pass the request/response to the next middleware in the stack. 您不能在结束响应后调用next(),而是要调用next(),以将请求/响应传递给堆栈中的下一个中间件。 Consider this example: 考虑以下示例:

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');
}

You need to call next() outside your if statement and also add a return to break out of the middleware's function scope if you don't want it to proceed. 您需要在if语句之外调用next()如果您不希望它继续执行,还需要添加一个返回值以超出中间件的功能范围。 next() is basically saying, don't stop at this middleware, move onto the next one. 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