最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - What is the correct way to "end" a request from expressconnect middleware? - Stack Overflow

programmeradmin1浏览0评论

Assuming I have middleware such as this;

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

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

    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 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?

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 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?
Share Improve this question edited May 18, 2023 at 15:35 Chenmunka 8157 gold badges25 silver badges31 bronze badges asked Mar 22, 2013 at 13:38 IsaacIsaac 1,7073 gold badges15 silver badges23 bronze badges
Add a comment  | 

1 Answer 1

Reset to default 36
  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.
发布评论

评论列表(0)

  1. 暂无评论