How to parse query string in Node.js?

Sometimes, we want to parse query string in Node.js.

In this article, we’ll look at how to parse query string in Node.js.

How to parse query string in Node.js?

To parse query string in Node.js, we can use the url module.

For instance, we write

const http = require('http');
const url = require('url');

const server = http.createServer((request, response) => {
  const {
    query: queryData
  } = url.parse(request.url, true);
  response.writeHead(200, {
    "Content-Type": "text/plain"
  });

  if (queryData.name) {
    response.end(queryData.name);
  } else {
    response.end("Hello World");
  }
});

server.listen(8000);

to call url.parse to parse the request.url value in the browser.

And we get the parsed query string values from the query property from the returned object.

Then we get the name query parameter value from queryData.name.

Conclusion

To parse query string in Node.js, we can use the url module.