Return to Snippet

Revision: 57963
at June 18, 2012 01:58 by chrisaiv


Initial Code
var express     = require("express"),
app         = express.createServer();

app.get("/", function( req, res ){
  //Strip out port number
  var hostname = ( req.headers.host.match(/:/g) ) ? req.headers.host.slice( 0, req.headers.host.indexOf(":") ) : req.headers.host

  res.render( "index.ejs", {
    layout:   false,
    hostname: "http://" + hostname
  });

});

Initial URL


Initial Description
I doubt anyone will ever need this but just in case.  I had a scenario where I needed to deliver the hostname (without the port) through an .ejs variable.  The hostname comes from the request header so that's easy to find and I simply used a .match with a ternary conditional to keep things clean.

Initial Title
NodeJS + ExpressJS: Strip out port from req.headers.host

Initial Tags


Initial Language
JavaScript