代码之家  ›  专栏  ›  技术社区  ›  DR01D

在node.js /Express为什么在next()之后有时需要return语句,有时不需要?

  •  0
  • DR01D  · 技术社区  · 8 年前

    req.query next() 触发下一个中间件。这是在不包括 return 后面的语句 下一个() 一切如期。

    app.get('/test', (req, res, next) => {
        if (req.query.name != 'cat') {
            next();
        } 
        res.send('it was cat');
    });
    
    app.get('/test', (req, res) => {
        res.send('it was not cat');
    });
    

    但是当我改变的时候 res.send 到 res.sendFile 在中间件的第二部分中,行为完全不同。

    app.get('/test', (req, res) => {
        res.sendFile(__dirname + '/public/index.html');
    });
    

    res.send('it was cat');

    这可以通过添加 返回 之后

    app.get('/test', (req, res, next) => {
        if (req.query.name != 'cat') {
            next();
            return;
        } 
        res.send('it was cat');
    });
    
    app.get('/test', (req, res) => {
        res.sendFile(__dirname + '/public/index.html');
    });
    

    为什么这会发生在有和没有 返回 声明?A 返回 res.sendFile res.send

    2 回复  |  直到 8 年前
        1
  •  3
  •   robertklep    8 年前

    这是在不包括 return 后面的语句 next()

    就像预期的那样,但事实并非如此。例如,如果您检索 /test 没有查询参数,或者查询参数不等于 name=cat ,Express将记录错误:

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

    我无法复制你的第二个例子;对我来说,它总是返回“it was cat”(在没有 ).

    任何Express处理程序/中间件的通用规则是:它应该 结束响应本身(通过调用 res.end , res.send , res.render res.sendFile 等) 使用传递请求 next . 对你来说,没有 返回 ,你两个都做。实际上,这样做的结果是不确定的。

        2
  •  2
  •   wberry    8 年前

    当你的听众表演 res.send('it was not cat') 请求的整个处理过程都是在不碰到蹦床的情况下进行的。这个 next() res.send(‘不是猫’) 饰面。所以到了 send('it was the cat') 已到达,响应已发送。

    res.sendFile() 响应的处理是异步的。文件必须读入内存,这是节点中的非阻塞I/O。将该I/O的回调放入事件队列,然后继续处理。所以 下一个() send('是猫')

    推荐文章