Skip to content

Instantly share code, notes, and snippets.

@GuyMograbi
Created July 21, 2017 16:03
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save GuyMograbi/e6bf25e56cd61c6a917e199bae29b46a to your computer and use it in GitHub Desktop.
Save GuyMograbi/e6bf25e56cd61c6a917e199bae29b46a to your computer and use it in GitHub Desktop.
absoluteUrl middleware in express
/**
*
* @description
* adds an <code>absoluteUrl</code> function on request
*
* <pre>
* var absoluteUrl = req.absoluteUrl('/myRelativeUrl'); //==> http://my.domain/myRelativeUrl
* </pre>
*
* and variable <code>origin</code> on request which will be equals to <code>http://my.domain</code>
*
* @param {object} req the request
* @param {object} res the response
* @param {function} next next middleware to operate
*/
exports.origin = function origin( req, res, next){
var _origin = req.protocol + '://' +req.get('Host') ;
req.origin = _origin;
// expects a URL from root "/some/page" which will result in "protocol://host:port/some/page"
req.absoluteUrl = function( relativeUrl ){
return _origin + relativeUrl;
};
next();
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment