Skip to content

Instantly share code, notes, and snippets.

@aweber1
Created April 4, 2020 12:16
Show Gist options
  • Save aweber1/f60b20a1daeb51f1c706e940fe330259 to your computer and use it in GitHub Desktop.
Save aweber1/f60b20a1daeb51f1c706e940fe330259 to your computer and use it in GitHub Desktop.
Node.js parse request url
import { IncomingMessage } from 'http';
import { TLSSocket } from 'tls';
import { URL } from 'url';
export function parseRequestUrl(req: IncomingMessage) {
let protocol = 'http';
if ((req.socket as TLSSocket).encrypted) {
protocol = 'https';
}
const baseUrl = `${protocol}://${req.headers.host}`;
if (!req.url) {
return new URL(baseUrl);
}
const parsedUrl = new URL(req.url, `${protocol}://${req.headers.host}`);
return parsedUrl;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment