Created
December 8, 2018 04:06
-
-
Save danielr18/f57cd4b3a55cb4117cb7e31d9bd92fc5 to your computer and use it in GitHub Desktop.
Absolute URL from req
This file contains hidden or 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
| import url from 'url' | |
| const defaultValidHostRegex = /www\.example\.com/ | |
| export function getProtocol(req) { | |
| let proto = req.connection.encrypted ? 'https' : 'http' | |
| // only do this if you trust the proxy | |
| proto = req.headers['x-forwarded-proto'] || proto | |
| return proto.split(/\s*,\s*/)[0] | |
| } | |
| export function getAbsoluteUrl(req, { fallbackHost = 'www.example.com', validHostRegex = defaultValidHostRegex } = {}) { | |
| let host = req.headers.host || '' | |
| if (!validHostRegex.test(host)) { | |
| host = fallbackHost | |
| } | |
| return url.format({ | |
| protocol: getProtocol(req), | |
| host, | |
| pathname: req.url | |
| }) | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment