【问题标题】:Nodejs https.request and axiosNodejs https.request 和 axios
【发布时间】: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) => {...});
}

但仍然不知道有什么区别。

【问题讨论】:

    标签: node.js https axios


    【解决方案1】:

    我会检查在 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() 方法中有不同的实现,它可以在发送到第 3 方 API 之前通过 url 编码来操作您的 sign 字符串。

    【讨论】:

    • 这也是我的猜测。最令人困惑的部分是具有相同参数的相同函数,但在不同场景中调用(由node xxx.js 直接运行脚本并由 RESTful API 触发)执行不同。不确定 HTTPS 构造函数发生了什么,在我在选项中定义主机名和路径而不是使用 URL 作为参数后它工作正常。如果有新发现,将深入研究源代码并在此处更新。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-09-15
    • 2019-05-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-03-29
    相关资源
    最近更新 更多