How to make a HTTP get request with query string parameters with Node.js?

Sometimes, we want to make a HTTP get request with query string parameters with Node.js.

In this article, we’ll look at how to make a HTTP get request with query string parameters with Node.js.

How to make a HTTP get request with query string parameters with Node.js?

To make a HTTP get request with query string parameters with Node.js, we can use the https.get method.

For instance, we write

const requestUrl = url.parse(url.format({
  protocol: 'https',
  hostname: 'example.com',
  pathname: '/the/path',
  query: {
    key: value
  }
}));

const req = https.get({
  hostname: requestUrl.hostname,
  path: requestUrl.path,
}, (res) => {
  // ...
})

to call url.parse to create a URL with the protocol, hostname, pathname and the query string parameters in the query property’s object.

Then we call https.get with an object with the hostname and path set to the hostname and path.

The path has the query string.

And we get the response from res in the callback.

Conclusion

To make a HTTP get request with query string parameters with Node.js, we can use the https.get method.