Good spot! url.parse() is now deprecated. To get URL parameters in Node.js, you can now use the below solution, which no longer requires importing the 'url' module: const http = require('http'); const server = http.createServer((req, res) => { // Create string of base URL (does not include path): const baseURL = `${req.protocol}://${req.headers.host}/`; // Create new URL object passing in relative path and the base URL: const url = new URL(req.url, baseURL); // URLSearchParams object is available on URL object, data parsed here to JS object: console.log(Object.fromEntries(url.searchParams)); // { var1: 'val', var2: 'val' } res.end(); }); server.listen(3000);
url parse is deprecated
Good spot! url.parse() is now deprecated. To get URL parameters in Node.js, you can now use the below solution, which no longer requires importing the 'url' module:
const http = require('http');
const server = http.createServer((req, res) => {
// Create string of base URL (does not include path):
const baseURL = `${req.protocol}://${req.headers.host}/`;
// Create new URL object passing in relative path and the base URL:
const url = new URL(req.url, baseURL);
// URLSearchParams object is available on URL object, data parsed here to JS object:
console.log(Object.fromEntries(url.searchParams));
// { var1: 'val', var2: 'val' }
res.end();
});
server.listen(3000);
Thanks for the comparison
You're welcome! I like using Express but I think it's also good to know the pure Node.js solution in case one needs to modify the Express behavior.