问题
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?
- 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?
回答1:
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.
来源:https://stackoverflow.com/questions/15571779/what-is-the-correct-way-to-end-a-request-from-express-connect-middleware