Created
April 4, 2020 12:16
-
-
Save aweber1/f60b20a1daeb51f1c706e940fe330259 to your computer and use it in GitHub Desktop.
Node.js parse request url
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
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