Created
July 21, 2017 16:03
-
-
Save GuyMograbi/e6bf25e56cd61c6a917e199bae29b46a to your computer and use it in GitHub Desktop.
absoluteUrl middleware in express
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* | |
* @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