2

我有一个非常简单的 nodejs 程序,用于演示与 Alchemer API 的通信。每当我运行以下代码时,代码都会引发错误ECONNREFUSED。但是,当我将相同的 url 复制到浏览器或 Postman 中时,它工作得很好。

注意 - 我注意到一件奇怪的事情,在错误的堆栈跟踪(见下文)中,它说地址是 127.0.0.1,即使我显然没有向我的本地主机发出请求......

Nodejs 代码段

require('dotenv').config();
const https = require('https');
const querystring = require('querystring');

console.log('Formulating query string...');

const params = {
    api_token: process.env.API_TOKEN,
    api_token_secret: process.env.API_TOKEN_SECRET
};

const reqArgs = querystring.stringify(params);

console.log('Query string: ', reqArgs);

const reqOptions  = {
    url: 'https://api.alchemer.com',
    path: '/v5/survey?' + reqArgs,
}

console.log('Test Url: ', reqOptions.url + reqOptions.path); // THIS WORKS IN THE 
BROWSER / POSTMAN
console.log('Getting data...');

https.request(reqOptions, resp => {
    let data = '';

    resp.on('data', chunk => {
        data += chunk;
    });

    resp.on('error', err => {
        console.error(JSON.stringify(err));
    });

    resp.on('end', () => {
        console.log('Request complete.');
        console.log(data);
    });
});

观察到的错误

events.js:292
      throw er; // Unhandled 'error' event
      ^

Error: connect ECONNREFUSED 127.0.0.1:443
    at TCPConnectWrap.afterConnect [as oncomplete] (net.js:1146:16)
Emitted 'error' event on ClientRequest instance at:
    at TLSSocket.socketErrorListener (_http_client.js:469:9)
    at TLSSocket.emit (events.js:315:20)
    at emitErrorNT (internal/streams/destroy.js:106:8)
    at emitErrorCloseNT (internal/streams/destroy.js:74:3)
    at processTicksAndRejections (internal/process/task_queues.js:80:21) {
  errno: -61,
  code: 'ECONNREFUSED',
  syscall: 'connect',
  address: '127.0.0.1',
  port: 443
}
4

1 回答 1

0

根据此处的https.requests文档,URL 似乎不是在请求选项中设置 URL 的正确属性名称。

考虑更改url您的reqOptionstohostnamehost

const reqOptions  = {
    hostname: 'https://api.alchemer.com',
    path: '/v5/survey?' + reqArgs,
}
于 2021-02-20T04:37:36.577 回答