Get URL Parameters in Node.js using Express and in pure Node.js

Поделиться
HTML-код
  • Опубликовано: 15 янв 2025

Комментарии • 4

  • @denysvynohradnyi5286
    @denysvynohradnyi5286 Год назад +2

    url parse is deprecated

    • @OpenJavaScript
      @OpenJavaScript  Год назад +1

      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);

  • @jxswxnth
    @jxswxnth Год назад +1

    Thanks for the comparison

    • @OpenJavaScript
      @OpenJavaScript  Год назад

      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.