如何修改Node.js HTTP模块服务,向Express服务发送可接收的JSON请求?
解决方案
首先要明确:HTTP GET请求规范中并不包含请求体,大部分HTTP服务器(包括Express默认配置)会忽略GET请求的body内容。所以要实现“发送JSON请求并让Express的GET接口接收”,存在规范冲突,更合理的做法是调整为POST请求,或者将参数放在URL查询字符串中。以下提供两种可行方案:
方案一:改为POST请求(推荐,符合HTTP规范)
1. 调整Express服务的接口方法
将app.get改为app.post,确保能正确接收请求体:
app.post("/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); } })
2. 修改HTTP模块服务代码
- 将请求方法改为
POST - 构造JSON格式的请求体,并手动设置
Content-Length头(Node.js的http.request要求必须指定) - 补充响应数据的接收逻辑,避免仅打印状态码
修改后的代码:
const http = require("http"); // 要发送的JSON查询数据 const postData = JSON.stringify({ address: "0xYourWalletAddress" // 替换为实际要查询的钱包地址 }); let options = { host: "127.0.0.1", port: 2020, path: "/wallet-status", method: "POST", // 切换为POST方法 headers: { "Content-Type": "application/json", "Content-Length": Buffer.byteLength(postData) // 必须指定内容长度 } }; const httpRequest = http.request(options, function(response) { let responseData = ""; // 分段接收响应数据 response.on("data", (chunk) => { responseData += chunk; }); // 响应结束后处理结果 response.on("end", () => { console.info("响应状态码:", response.statusCode); console.info("响应内容:", JSON.parse(responseData)); }); }); // 写入JSON请求体 httpRequest.write(postData); httpRequest.end();
方案二:坚持使用GET请求(不推荐,不符合HTTP规范)
如果一定要保留GET请求,需将参数放在URL的查询字符串中,而非请求体:
1. 调整Express服务的参数获取逻辑
从req.query中读取地址,替代req.body:
app.get("/wallet-status",function(req,res){ try{ const response=walletView(req.query.address); // 改为从URL查询参数取地址 res.status(200).json(response); }catch(err){ const errorObj={ error:err.name, message:err.message } res.status(400).json(errorObj); } })
2. 修改HTTP模块服务代码
- 在
path中拼接查询参数 - 无需设置请求体相关的头和内容
修改后的代码:
const http = require("http"); const targetAddress = "0xYourWalletAddress"; // 替换为实际钱包地址 let options = { host: "127.0.0.1", port: 2020, path: `/wallet-status?address=${encodeURIComponent(targetAddress)}`, // 拼接查询参数 method: "GET", headers: { "Content-Type": "application/json" // 可保留,但GET请求实际不需要请求体 } }; const httpRequest = http.request(options, function(response) { let responseData = ""; response.on("data", (chunk) => { responseData += chunk; }); response.on("end", () => { console.info("响应状态码:", response.statusCode); console.info("响应内容:", JSON.parse(responseData)); }); }); httpRequest.end();
内容的提问来源于stack exchange,提问作者Alireza
相关产品推荐
相关产品推荐

