【发布时间】:2021-07-08 23:50:04
【问题描述】:
我在使用 Nodejs https 模块时遇到了一个非常奇怪的问题。
我试图做的是,为某些服务调用第 3 方 API,以下是我的代码:
const https = require("https");
function request(accessId, secretKey, host, api, body, timeout=3000) {
let bodyString = JSON.stringify(body);
let time = Math.round(new Date().getTime()/1000).toString();
// I have implemented the signBody function
let sign = signBody(accessId, secretKey, time, bodyString);
let header = {
"Content-Type": "application/json",
"AccessId": accessId,
"TimeStamp": time,
"Sign": sign,
};
let options = {
method: 'POST',
timeout: timeout,
headers: header,
}
let url = new URL(api,host);
https.request(url, options, (res) => {...});
}
他们奇怪的部分是,如果我通过node xxx.js 运行函数来触发request("MY_ACCESS_ID", "MY_SECRET_KEY", "https://api.xxxx.com", "/service/api/v3", MY_BODY) 函数,它会按预期工作。但是,这个request(...) 函数是我的网络服务器的一部分,它由一个API(我使用的是express.js)使用,例如:
// the myService implemented the request() function
let myService = require("./myService.js")
router.get("/myAPI", (req, res, next) => {
request("MY_ACCESS_ID", "MY_SECRET_KEY", "https://api.xxxx.com", "/service/api/v3", MY_BODY)
})
它总是显示错误:Error: connect ECONNREFUSED 127.0.0.1:443
我不知道为什么相同的代码表现不同。我认为这可能是 https.request 问题。他们我尝试使用 axios 进行发布请求。其他奇怪的事情出现了。通过使用完全相同的标头,https.request() 从服务提供者返回成功,axios.post 返回错误消息:Sign check error, please check the way to generate Sign。
这太疯狂了……不知道这个问题。任何想法 ?? 顺便说一句,我已经通过实施解决了这个问题:
const https = require("https");
function request(accessId, secretKey, host, api, body, timeout=3000) {
let bodyString = JSON.stringify(body);
let time = Math.round(new Date().getTime()/1000).toString();
// I have implemented the signBody function
let sign = signBody(accessId, secretKey, time, bodyString);
let header = {
"Content-Type": "application/json",
"AccessId": accessId,
"TimeStamp": time,
"Sign": sign,
};
let options = {
hostname: host,
path: api,
method: 'POST',
timeout: timeout,
headers: header,
}
https.request(options, (res) => {...});
}
但仍然不知道有什么区别。
【问题讨论】: