Skip to content

Instantly share code, notes, and snippets.

@ajmas
Last active March 25, 2020 17:07
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 ajmas/53428a01d1ff6de6c0d86745b11b9012 to your computer and use it in GitHub Desktop.
Save ajmas/53428a01d1ff6de6c0d86745b11b9012 to your computer and use it in GitHub Desktop.
Various HTTP related utilities in node js, specifically in Typescript
import { Request } from 'express';
function isTrue(value) {
return ['1', 1, 'yes', 'true', 'on'].indexOf(value) > -1;
}
function booleanValue(value) {
if (value) {
return ['1', 1, 'yes', 'true', 'on'].indexOf(value) > -1;
}
return undefined;
}
function getBaseUrl(req: Request) {
let proto = req.headers['x-forwarded-proto'] || req.protocol;
if (proto && Array.isArray(proto)) {
proto = proto[0];
}
let host = req.headers['x-forwarded-host'] || req.get('host');
if (host && Array.isArray(host)) {
host = host[0];
}
let url = proto + '://' + host;
let port = req.get('port');
if (port) {
url += ':' + port;
}
return url;
}
function getRemoteHost(req: Request) {
return req.headers['x-forwarded-for'] || req.connection.remoteAddress;
}
export {
isTrue,
booleanValue,
isRefererSameSite,
getBaseUrl,
getRemoteHost
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment