Redirect all requests using Express 3?

余生颓废 提交于 2019-12-05 13:38:15

Since Express 3 doesn't use its own HTTP server (instead you pass your app to http.createServer), it doesn't know what port it's running on unless you tell it. That said, you can do basically what you want to do with the following:

app.use(function(request, response, next) {
  var newHost = request.host.replace(/^www\./, '');
  if (request.host != newHost) {
    // 301 is a "Moved Permanently" redirect.
    response.redirect(301, request.protocol + "://" + newHost + request.url);
  } else {
    next();
  }
});

You could export this in a module and wrap it in a generator that takes a port:

// no_www.js

module.exports = function(port) {
  app.use(function(request, response, next) {
    var newHost = request.host.replace(/^www\./, '');
    if (request.host != newHost) {
      var portStr = '';
      if (request.protocol == 'http' && port != 80) portStr = ':' + port;
      if (request.protocol == 'https' && port != 443) portSt r= ':' + port;
      // 301 is a "Moved Permanently" redirect.
      response.redirect(301, request.protocol + "://" + newHost + portStr + request.url);
    } else {
      next();
    }
  });
}

// app.js

var noWww = require('./no_www');
var app = express();

app.configure("development", function() {
  app.set("port", 3000);
});

...

app.use(noWww(app.get('port')));
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!