ExpressJS - 从中​​间件发送响应

tve*_*his 2 node.js express

对于发生的每个请求,我想检查是否设置了查询字符串中的参数。如果没有,应用程序应该发送特定的消息;否则,根据需要进行路由。

app.js

app.use(function(req,res,next){
    if(req.query.key === undefined) {
        res.send("Sorry!");
    }
    req.db = db;
    next();
});

app.use('/', routes);
Run Code Online (Sandbox Code Playgroud)

'/'请求不带参数时,Sorry!显示。但是,我的 ExpressJS 应用程序因以下错误而崩溃:

Error: Can't set headers after they are sent.

我不完全确定为什么会发生这种情况。我尝试将支票移至 中的路线本身index.js,但我仍然遇到相同的错误。

Ben*_*une 7

那是因为您仍在继续执行和调用next(),这将移动到堆栈中的下一个中间件或路由。

早点返回以阻止它移动到下一个中​​间件。

app.use(function(req,res,next){
    if(req.query.key === undefined) {
        //return out of the function here
        return res.send("Sorry!");
    }
    req.db = db;
    next();
});

app.use('/', routes);
Run Code Online (Sandbox Code Playgroud)