Posted By

chrisaiv on 06/18/12


Tagged

nodejs


Versions (?)

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


 / Published in: JavaScript
 

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.

  1. var express = require("express"),
  2. app = express.createServer();
  3.  
  4. app.get("/", function( req, res ){
  5. //Strip out port number
  6. var hostname = ( req.headers.host.match(/:/g) ) ? req.headers.host.slice( 0, req.headers.host.indexOf(":") ) : req.headers.host
  7.  
  8. res.render( "index.ejs", {
  9. layout: false,
  10. hostname: "http://" + hostname
  11. });
  12.  
  13. });

Report this snippet  

You need to login to post a comment.