node.js - Nodejs https.request 和 axios
问题描述
https
通过使用 Nodejs模块,我遇到了一个非常奇怪的问题。我想做的是,为某些服务调用第 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 进行发布请求。其他奇怪的事情出现了。通过使用完全相同的 header,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) => {...});
}
但仍然不知道有什么区别。
解决方案
我会检查在 https.request 方法中构造的最终 url。非工作版本向 发出请求127.0.0.1:443
,由于您的本地主机不支持 https(仅 http)并且 443 通常用于 https,因此该请求不起作用。
有关默认端口号,请参阅https://nodejs.org/api/https.html#https_https_request_url_options_callback。
Axios 在 post() 方法中有不同的实现,它可以sign
在发送到 3rd-party API 之前通过 url 编码来操作你的字符串。
推荐阅读
- gcc - 不同的函数调用程序集与 -O0 和 -O1 与 ARM 上的 GCC
- prometheus - 如何防止 Prometheus 向指定目标添加端口?
- amazon-cognito - 读/写到 Cognito DeveloperOnlyAttribute
- python - 基于直方图的图像噪声估计
- python - Selenium代理连接,为什么ip不改变?
- android - 为什么 Jenkins 在不同的文件夹中搜索 Android SDK 工具?
- javascript - 使用超链接后如何显示相同 id 的 tabcontent?
- docker - 如何运行/托管:使用 docker-compose 在同一台机器上运行多个环境
- dataframe - 将多个 Dataframe 行转换为一行
- c++ - 当 `std::make_index_sequence` 和 `std::index_sequence` 用于模板参数默认类型时,g++ 和 clang++ 的不同行为