Node.js - Parse request URL

by
Jeremy Canfield |
Updated: July 22 2024
| Node.js articles
If you have not yet installed Node.js, check out my article Install Node.js on Linux.
Let's say you have a file named app.js that contains the following.
const url = require("url");
const returnurl = function (req, res) {
const myurl = new URL(`http://www.example.com:12345/index.html?id=123`);
return myurl
}
const foo = returnurl();
console.log(foo);
Running app.js should return something like this.
URL {
href: 'http://www.example.com:12345/index.html?id=123',
origin: 'http://www.example.com:12345',
protocol: 'http:',
username: '',
password: '',
host: 'www.example.com:12345',
hostname: 'www.example.com',
port: '12345',
pathname: '/index.html',
search: '?id=123',
searchParams: URLSearchParams { 'id' => '123' },
hash: ''
}
And here is how you could return the non-dictionary keys.
const url = require("url");
const returnhostname = function (req, res) {
const myurl = new URL(`http://www.example.com:12345/index.html?id=123`);
return myurl
}
const foo = returnurl();
console.log(foo);
Which in this example should return www.example.com.
~]$ node app.js
www.example.com
And here is how you can return one of the searchParams.
const { URL, URLSearchParams } = require('url');
const return_id = function (req, res) {
const myurl = new URL(`http://www.example.com:12345/index.html?id=123`);
return myurl.searchParams.get('id');
}
const id = return_id();
console.log(id);
Which in this example should return 123.
~]$ node app.js
123
Did you find this article helpful?
If so, consider buying me a coffee over at