Categories
JavaScript Answers

How to parse Query String in Node.js?

Spread the love

To parse Query String in Node.js, we use the querystring module.

For instance, we write

const http = require("http");
const queryString = require("querystring");

http
  .createServer((oRequest, oResponse) => {
    let oQueryParams;
    if (oRequest.url.indexOf("?") >= 0) {
      oQueryParams = queryString.parse(oRequest.url.replace(/^.*\?/, ""));
      console.log(oQueryParams);
    }

    oResponse.writeHead(200, { "Content-Type": "text/plain" });
    oResponse.end("Hello world.");
  })
  .listen(3000, "127.0.0.1");

to call queryString.parse to parse the request URL that we got from oRequest.url.

We get pack an object with the keys and values of the query string.

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

Leave a Reply

Your email address will not be published. Required fields are marked *