javascript “结束”来自 express/connect 中间件的请求的正确方法是什么?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/15571779/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-27 01:12:52  来源:igfitidea点击:

What is the correct way to "end" a request from express/connect middleware?

javascriptnode.jsexpressconnect

提问by Isaac

Assuming I have middleware such as this;

假设我有这样的中间件;

var express = require('express');
var app = express();

app.use(function (req, res, next) {
    var host = "example.com";

    if (req.host !== host) {
        res.redirect(301, host + req.originalUrl);
        res.end();
    }
});

What sort of rules do I need to abide by here?

我在这里需要遵守什么样的规则?

  1. Should I be calling res.end()? (or does res.redirect()do this for me?)
  2. Should I be calling next()? (or does connect detect the request has ended and exit cleanly?)
  3. Assuming that I shouldbe calling next(), I guess that means Ican potentially be receiving requests to my middleware which may have already been ended by other middleware higher in the chain; how do I protect myself against this?
  1. 我应该打电话res.end()吗?(或者res.redirect()为我做这个?)
  2. 我应该打电话next()吗?(或者连接是否检测到请求已经结束并干净地退出?)
  3. 假设我应该调用next(),我想这意味着可能会收到对我的中间件的请求,这些请求可能已经被链中更高的其他中间件终止了;我该如何保护自己免受这种伤害?

回答by robertklep

  1. res.redirect()indeed calls res.end()itself;
  2. You should call next()if your middleware isn't the end point; in the case of generating a redirect, it isan endpoint and next()shouldn't be called, but if req.host === host, you need to call next()to move the request up the chain to other middleware/routes;
  3. A request doesn't get ended, a response does. And when it does, it will end the middleware chain so you don't have to worry about it.
  1. res.redirect()确实res.end()自称;
  2. next()如果您的中间件不是终点,您应该调用;在生成重定向的情况下,它一个端点,next()不应调用,但如果req.host === host,则需要调用next()以将请求沿链向上移动到其他中间件/路由;
  3. 请求不会结束,响应会结束。当它发生时,它将结束中间件链,因此您不必担心。