Skip to content

Instantly share code, notes, and snippets.

@DanboDuan
Forked from aweber1/parseRequestUrl.js
Created October 29, 2022 02:21
Show Gist options
  • Save DanboDuan/e3e2790208fb228fb2b38d0a897fab49 to your computer and use it in GitHub Desktop.
Save DanboDuan/e3e2790208fb228fb2b38d0a897fab49 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