结束“结束”的正确方法是什么?快速/连接中间件的请求? [英] What is the correct way to "end" a request from express/connect middleware?
本文介绍了结束“结束”的正确方法是什么?快速/连接中间件的请求?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
假设我有这样的中间件;
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();
}
});
我需要遵守哪些规则?
- 我应该打电话给
res.end()
吗? (或者res.redirect()
为我这样做吗?) - 我应该打电话给
next( )
? (或者connect是否检测到请求已结束并干净地退出?) - 假设我应该正在调用
next()
,我想这意味着 I 可能正在接收对我的中间件的请求,该请求可能已经被链中其他较高层的中间件终止了;如何保护自己免受此侵害?
- Should I be calling
res.end()
? (or doesres.redirect()
do this for me?) - Should I be calling
next()
? (or does connect detect the request has ended and exit cleanly?) - 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?
推荐答案
-
res.redirect()
确实会调用res.end()
本身; - 您如果中间件不是终点,应该调用
next()
;在生成重定向的情况下,它是一个端点,并且不应该调用next()
,但是如果req.host === host
,您需要调用next()
将请求沿链移动到其他中间件/路由; - 请求不会终止,响应会终止。这样做的时候,它将终止中间件链,因此您不必担心。
res.redirect()
indeed callsres.end()
itself;- You should call
next()
if your middleware isn't the end point; in the case of generating a redirect, it is an endpoint andnext()
shouldn't be called, but ifreq.host === host
, you need to callnext()
to move the request up the chain to other middleware/routes; - 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屋!
查看全文