Making HTTP Requests
Making HTTP Requests in Node.js
HTTP or Hypertext Transfer Protocol is the foundation of any data exchange on the web. When it comes to Node.js, making HTTP requests is a core functionality that allows it to communicate with other servers. In this tutorial, we will learn how to make HTTP requests using Node.js.
HTTP Module in Node.js
Node.js has a built-in module called HTTP, which allows Node.js to transfer data over the Hyper Text Transfer Protocol (HTTP). You do not need to install this module as it comes packaged with Node.js.
Here is a simple implementation of an HTTP GET request:
const http = require('http');
http.get('http://api.example.com/data', (resp) => {
let data = '';
// A chunk of data has been received.
resp.on('data', (chunk) => {
data += chunk;
});
// The whole response has been received.
resp.on('end', () => {
console.log(JSON.parse(data));
});
}).on("error", (err) => {
console.log("Error: " + err.message);
});
In the example above, we start by importing the http
module. We then use the http.get
method to send a GET request to the specified URL. The response (resp
) from the server is an object that we listen to. Specifically, we listen to two events: data
and end
. The data
event is emitted whenever the server sends some data. We append this data to our previously defined data
variable. The end
event is emitted when all the data has been received. At this point, we parse the data as JSON and log it to the console.
Making POST Requests
Making a POST request is slightly more complicated than a GET request. With a POST request, you need to include data to be sent to the server in the request body.
Here is a simple implementation of an HTTP POST request:
const http = require('http');
const data = JSON.stringify({
todo: 'Buy the milk'
});
const options = {
hostname: 'api.example.com',
port: 80,
path: '/todos',
method: 'POST',
headers: {
'Content-Type': 'application/json',
'Content-Length': data.length
}
};
const req = http.request(options, (res) => {
let body = '';
res.on('data', (chunk) => {
body += chunk;
});
res.on('end', () => {
console.log('Server response: ', body);
});
});
req.on('error', (error) => {
console.error('Problem with request: ', error.message);
});
// Write data to request body
req.write(data);
req.end();
In the example above, we first define the data we want to send to the server. We then define options object specifying details of our POST request. We make the request with http.request
and listen for response data in a similar way to our GET example. The main difference is that we need to write data to the request body with req.write(data)
.
And that's it! You've now learned how to make HTTP GET and POST requests in Node.js. Happy coding!