DZone
Thanks for visiting DZone today,
Edit Profile
  • Manage Email Subscriptions
  • How to Post to DZone
  • Article Submission Guidelines
Sign Out View Profile
  • Post an Article
  • Manage My Drafts
Over 2 million developers have joined DZone.
Log In / Join
Please enter at least three characters to search
Refcards Trend Reports
Events Video Library
Refcards
Trend Reports

Events

View Events Video Library

Zones

Culture and Methodologies Agile Career Development Methodologies Team Management
Data Engineering AI/ML Big Data Data Databases IoT
Software Design and Architecture Cloud Architecture Containers Integration Microservices Performance Security
Coding Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks
Culture and Methodologies
Agile Career Development Methodologies Team Management
Data Engineering
AI/ML Big Data Data Databases IoT
Software Design and Architecture
Cloud Architecture Containers Integration Microservices Performance Security
Coding
Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance
Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks

Last call! Secure your stack and shape the future! Help dev teams across the globe navigate their software supply chain security challenges.

Modernize your data layer. Learn how to design cloud-native database architectures to meet the evolving demands of AI and GenAI workloads.

Releasing software shouldn't be stressful or risky. Learn how to leverage progressive delivery techniques to ensure safer deployments.

Avoid machine learning mistakes and boost model performance! Discover key ML patterns, anti-patterns, data strategies, and more.

Related

  • RESTful Web Services: How To Create a Context Path for Spring Boot Application or Web Service
  • Building REST API Backend Easily With Ballerina Language
  • How To Validate HTTP Post Request Body - Restful Web Services With Spring Framework | Spring Boot
  • RESTful Web Services With Spring Boot: Reading HTTP POST Request Body

Trending

  • Unmasking Entity-Based Data Masking: Best Practices 2025
  • AI-Based Threat Detection in Cloud Security
  • How Trustworthy Is Big Data?
  • Streamlining Event Data in Event-Driven Ansible
  1. DZone
  2. Coding
  3. Frameworks
  4. Node.js Http Module to Consume Spring RESTful Web Application

Node.js Http Module to Consume Spring RESTful Web Application

By 
Divya M user avatar
Divya M
·
Jun. 08, 20 · Tutorial
Likes (3)
Comment
Save
Tweet
Share
11.4K Views

Join the DZone community and get the full member experience.

Join For Free

Modules 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:

  1. Core/Built-in module - One of the module is HTTP.
  2. External/Third-Party module.
  3. 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:

JavaScript
xxxxxxxxxx
1
20
 
1
const http = require("http");
2
3
http
4
  .get("http://localhost:8080/product/controller/getDetails", (resp) => {
5
    let data = "";
6
7
    // A chunk of data has been recieved. Append it with the previously retrieved chunk of data
8
    resp.on("data", (chunk) => {
9
      data += chunk;
10
    });
11
12
    // when the whole response is received, parse the result and Print it in the console
13
    resp.on("end", () => {
14
      console.log(JSON.parse(data));
15
    });
16
  })
17
  .on("error", (err) => {
18
    console.log("Error: " + err.message);
19
  });
20


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.

JSON
xxxxxxxxxx
1
 
1
[
2
  {
3
    id: 1001,
4
    name: 'Herbal Handwash',
5
    description: 'Handwash',
6
    price: 138.09
7
  }
8
]
9


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:

JavaScript
x
41
 
1
const http = require("http");
2
//data to send in JSON format
3
const data = JSON.stringify({
4
  name: "Sanitizer",
5
  description: "Herbal Sanitizer",
6
  price: 230,
7
});
8
//url, method type, headers like content-type and data to send
9
const options = {
10
  host: "localhost",
11
  port: 8080,
12
  path: "/product/controller/addProduct",
13
  method: "POST",
14
  headers: {
15
    "Content-Type": "application/json",
16
    "Content-Length": data.length,
17
  },
18
};
19
20
const req = http.request(options, (res) => {
21
  //status code of the request sent
22
  console.log("statusCode: ", res.statusCode);
23
  let result = "";
24
  // A chunk of data has been recieved. Append it with the previously retrieved chunk of data
25
  res.on("data", (chunk) => {
26
    result += chunk;
27
  });
28
  //The whole response has been received. Display it into the console.
29
  res.on("end", () => {
30
    console.log("Result is: " + result);
31
  });
32
});
33
//error if any problem with the request
34
req.on("error", (err) => {
35
  console.log("Error: " + err.message);
36
});
37
//write data to request body
38
req.write(data);
39
//to signify the end of the request - even if there is no data being written to the request body.
40
req.end();
41


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: 

  1. PUT and DELETE requests can also be sent in the same way.
  2. The only difference between http.get() and http.request() is that it sets the method to GET, and calls req.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. 

Spring Framework application REST Web Protocols Data event Web application Requests Node.js Web Service

Opinions expressed by DZone contributors are their own.

Related

  • RESTful Web Services: How To Create a Context Path for Spring Boot Application or Web Service
  • Building REST API Backend Easily With Ballerina Language
  • How To Validate HTTP Post Request Body - Restful Web Services With Spring Framework | Spring Boot
  • RESTful Web Services With Spring Boot: Reading HTTP POST Request Body

Partner Resources

×

Comments
Oops! Something Went Wrong

The likes didn't load as expected. Please refresh the page and try again.

ABOUT US

  • About DZone
  • Support and feedback
  • Community research
  • Sitemap

ADVERTISE

  • Advertise with DZone

CONTRIBUTE ON DZONE

  • Article Submission Guidelines
  • Become a Contributor
  • Core Program
  • Visit the Writers' Zone

LEGAL

  • Terms of Service
  • Privacy Policy

CONTACT US

  • 3343 Perimeter Hill Drive
  • Suite 100
  • Nashville, TN 37211
  • support@dzone.com

Let's be friends:

Likes
There are no likes...yet! 👀
Be the first to like this post!
It looks like you're not logged in.
Sign in to see who liked this post!