Node.js Http Module to Consume Spring RESTful Web Application
Join the DZone community and get the full member experience.
Join For FreeModules in Node.js
Modules are otherwise called as packages in Node.js. Module is a collection of one or more JavaScript files to serve complex functionality. There are 3 types of modules:
- Core/Built-in module - One of the module is HTTP.
- External/Third-Party module.
- User-defined module.
Consider we have created a Spring RESTful web application using Spring Boot. We can use Node's HTTP module to send all types of HTTP requests and receive responses — no need to add any third-party module to our Node application.
Note: I have used Spring Boot 2.1.x, Java 11 to create Spring REST application and MySQL to connect to the database.
This article describes how to use Node.js Http Core Module to send HTTP GET/POST/PUT/DELETE requests to Spring REST API and receive the response.
HTTP Module
Using this module, we can make HTTP requests (GET, POST, PUT and DELETE) and can create an HTTP server that listens on a particular port and sends responses back to the client.
GET Request
Syntax: http.get(url[, options][, callback])
Used to send GET request and returns ClientRequest.
ClientRequest
object emits events that we can listen in order to manipulate the response body.url
– can be String / URL Object.options
– are optional. Holds information like headers, host, hostname, port, path with the http method always set to GET.callback
– function to handle different events of the returned response. Instead of just reading the data from the response, we add a callback method to the data event of the response. This will be called every time whenever another piece of data arrives. Once after all that data has arrived, we should finish our response. Hence, we also add a callback for the end event of the response and in that callback we can manipulate the data received.
Example:
xxxxxxxxxx
const http = require("http");
http
.get("http://localhost:8080/product/controller/getDetails", (resp) => {
let data = "";
// A chunk of data has been recieved. Append it with the previously retrieved chunk of data
resp.on("data", (chunk) => {
data += chunk;
});
// when the whole response is received, parse the result and Print it in the console
resp.on("end", () => {
console.log(JSON.parse(data));
});
})
.on("error", (err) => {
console.log("Error: " + err.message);
});
In the above example, the http.get()
method is used to send HTTP GET request to the Spring REST API endpoint (http://localhost:8080/product/controller/getDetails) mentioned in the first parameter. The second parameter is a callback to listen to the events on ClientRequest
.
We added a callback method to the data event. This will be called every time whenever another piece of data arrives. In our example, we also added a callback for the end event once after all the data is received, and, in that callback, we have converted the data received into JSON format.
We have an error event also, which will be executed when the request is not made properly.
After we execute the above example, we can observe the console. JSON data returned by the Spring REST API is displayed as follows.
xxxxxxxxxx
[
{
id: 1001,
name: 'Herbal Handwash',
description: 'Handwash',
price: 138.09
}
]
POST Request
Syntax: http.request(options[,callback])
- To make a post request, we have to use the generic http.request() method
- there is no http.post() method.
- options – it can be an object literal, a string or a URL object.
- callback – the callback function to capture and process the response.
Example:
const http = require("http");
//data to send in JSON format
const data = JSON.stringify({
name: "Sanitizer",
description: "Herbal Sanitizer",
price: 230,
});
//url, method type, headers like content-type and data to send
const options = {
host: "localhost",
port: 8080,
path: "/product/controller/addProduct",
method: "POST",
headers: {
"Content-Type": "application/json",
"Content-Length": data.length,
},
};
const req = http.request(options, (res) => {
//status code of the request sent
console.log("statusCode: ", res.statusCode);
let result = "";
// A chunk of data has been recieved. Append it with the previously retrieved chunk of data
res.on("data", (chunk) => {
result += chunk;
});
//The whole response has been received. Display it into the console.
res.on("end", () => {
console.log("Result is: " + result);
});
});
//error if any problem with the request
req.on("error", (err) => {
console.log("Error: " + err.message);
});
//write data to request body
req.write(data);
//to signify the end of the request - even if there is no data being written to the request body.
req.end();
In the above example, the http.request()
method is used to send HTTP POST request to the Spring REST API endpoint. Define the data which we must send along with the POST request to Spring REST API.
As our Spring Rest application needs data in JSON format, created data, assigned the JSON value into it. We must set the values like information port number, host name, path, request method type, headers in the options, which can be used to send the request, mentioned in the first parameter. Here we are sending request to “http://localhost:8080/product/controller/addProduct”. The second parameter is a callback to listen to the events on ClientRequest.
We added a callback method to the data event. This will be called every time whenever another piece of data arrives. In our example,
we also added a callback for the end event once after all the data is received and, in that callback, we have converted the data received into JSON format.
We have error event also, which will be executed when the request is not made properly. Req.write(data)
here is used to write data to the request body.
With req.end()
, we call the end()
method to indicate that we are done handling the request and the response can be sent to the user who made the http request.
After we execute the above example, we can observe the console.
Result is: Product added successfully with id:1002.
We can observe the data inserted in the table connected with the Spring rest application.
Note:
- PUT and DELETE requests can also be sent in the same way.
- The only difference between
http.get()
andhttp.request()
is that it sets the method to GET, and callsreq.end()
automatically.
If you want to see the complete code of the Spring Rest application, which I consumed here, please refer my another article “Java 11 HTTP Client API to Consume Restful Web Service Created Using Spring Boot”.
Conclusion
With the help of Http module in Node.js, we can send different types of HTTP requests to Spring Rest API. No need to add any external library to our application. Using this Http module, we are required to receive the response in chunks and execute a callback function when all the data is received. And We also need to parse the response data.
Opinions expressed by DZone contributors are their own.
Comments