Search code examples
node.jsjsonexpresshttprequest

How to send a request at JSON format using http module of NodeJS?


Two web servers are in place: one is developed using the Express.js framework to manage requests and responses, while the other is built with the HTTP module to forward requests to the former. The current requirement is to send requests in JSON format, but there is uncertainty on how to achieve this using the HTTP module.

The first server by express js:

const { Web3 } = require("web3");
const {toChecksumAddress}=require("ethereum-checksum-address");
const express=require("express");
const bodyParser=require("body-parser");

const walletMap=new Map();

const urlencodedParser=new bodyParser.urlencoded({extended:false});
const app=express();
app.use(bodyParser.json());

...

app.get("/wallet-status",function(req,res){
  try{
    const response=walletView(req.body.address);
    res.status(200).json(response);
  }catch(err){
    const errorObj={
      error:err.name,
      message:err.message
    }
    res.status(400).json(errorObj);
  }
})

...

function walletView(address){
    address=address.toString();
    if(toChecksumAddress(address)){
      if(walletMap.get(address)===undefined){
        return {"message":"The address provided has not been recorded previously"}
      }else{
        return walletMap.get(address);
      }
    }
}

The second server by http module:

const http=require("http");

let options={
    host:"127.0.0.1",
    port:2020,
    path:"/wallet-status",
    method:"GET",
    headers:{
        "Content-Type":"application/json"
    }
}

const httpRequest=http.request(options,function(response){
    console.info(response.statusCode);
})

httpRequest.end();

What modifications are needed for the second app to send JSON requests, allowing the callback function of app.get("/wallet-status",...) to receive them?


Solution

  • What modifications are needed for the second app to send JSON requests, allowing the callback function of app.get("/wallet-status",...) to receive them?

    You need to modify options object to include the JSON payload in request.

    Here's how:

    const http = require("http");
    
    let data = JSON.stringify({ address: "your_address_here" });
    
    let options = {
        host: "127.0.0.1",
        port: 2020,
        path: "/wallet-status",
        method: "POST", // Change method to POST for sending JSON data.
        headers: {
            "Content-Type": "application/json",
            "Content-Length": data.length
        }
    };
    
    const httpRequest = http.request(options, function(response) {
        let responseData = '';
        response.on('data', function(chunk) {
            responseData += chunk;
        });
    
        response.on('end', function() {
            console.log(JSON.parse(responseData));
        });
    });
    
    httpRequest.write(data); // Send JSON data in the request body.
    httpRequest.end();
    

    (HTTP protocol verbs)