To send query parameters in a GET request in Node.js, you can use the built-in http
or https
modules, or you can use a third-party library like axios
, request
, or superagent
. Here’s an example using the http
module:
const http = require('http');
const options = {
hostname: 'example.com',
port: 80,
path: '/data?id=123&name=John+Doe',
method: 'GET'
};
const req = http.request(options, res => {
console.log(`statusCode: ${res.statusCode}`);
res.on('data', d => {
process.stdout.write(d);
});
});
req.on('error', error => {
console.error(error);
});
req.end();
In this example, we’re using the http
module to make a GET request to the example.com
server with query parameters id
and name
. We create an options
object with the hostname
, port
, path
, and method
properties, and we pass it on to the http.request()
method.
We listen for the data
event on the response object to log the response body to the console, and we listen for the error
event to log any errors to the console.
Finally, we call the req.end()
method to send the request.