如何使用NodeJS的http模块发送JSON格式的请求?

问题描述 投票:0回答:1

有两个Web服务器:一个是使用Express.js框架开发的,用于管理请求和响应,另一个是使用HTTP模块构建的,用于将请求转发给前者。目前的需求是以 JSON 格式发送请求,但是如何使用 HTTP 模块来实现这一点还存在不确定性。

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);
      }
    }
}

http模块的第二个服务器:

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();

第二个应用程序发送 JSON 请求需要进行哪些修改,以便 app.get("/wallet-status",...) 的回调函数能够接收它们?

node.js json express http request
1个回答
0
投票

第二个应用程序发送 JSON 请求需要进行哪些修改,以便 app.get("/wallet-status",...) 的回调函数能够接收它们?

您需要修改

options
对象以在请求中包含 JSON 负载。

具体方法如下:

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 协议动词)

© www.soinside.com 2019 - 2024. All rights reserved.