gpt4 book ai didi

javascript - 如何通过 Node.js Express 使用多个请求处理功能?

转载 作者:行者123 更新时间:2023-12-02 16:44:52 24 4
gpt4 key购买 nike

我需要在我的应用程序中的大多数路由中执行重复的身份验证过程。我决定为其提供一些结构,并在中间件函数中完成重复的工作。

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

所以,而不是:

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

关于javascript - 如何通过 Node.js Express 使用多个请求处理功能?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27186120/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com