结束“结束”的正确方法是什么?快速/连接中间件的请求? [英] What is the correct way to "end" a request from express/connect middleware?

查看:73
本文介绍了结束“结束”的正确方法是什么?快速/连接中间件的请求?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设我有这样的中间件;

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

我需要遵守哪些规则?


  1. 我应该打电话给 res.end()吗? (或者 res.redirect()为我这样做吗?)

  2. 我应该打电话给 next( )? (或者connect是否检测到请求已结束并干净地退出?)

  3. 假设我应该正在调用 next(),我想这意味着 I 可能正在接收对我的中间件的请求,该请求可能已经被链中其他较高层的中间件终止了;如何保护自己免受此侵害?

  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 should be calling next(), I guess that means I can 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.redirect()确实会调用 res.end()本身;

  2. 您如果中间件不是终点,应该调用 next();在生成重定向的情况下,它一个端点,并且不应该调用 next(),但是如果 req.host === host ,您需要调用 next()将请求沿链移动到其他中间件/路由;

  3. 请求不会终止,响应会终止。这样做的时候,它将终止中间件链,因此您不必担心。

  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 is an 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.

这篇关于结束“结束”的正确方法是什么?快速/连接中间件的请求?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆