首页 > 解决方案 > 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 进行发布请求。其他奇怪的事情出现了。通过使用完全相同的 headerhttps.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.jshttpsaxios

解决方案


我会检查在 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 编码来操作你的字符串。


推荐阅读