1

我有一个非常简单的 nodejs 程序,用于演示与 Alchemer API 的通信。每当我运行以下代码时,都会有几秒钟的延迟,然后会抛出带有标识符的错误ECONNRESET。但是,当我将相同的 url 复制到浏览器或 Postman 中时,它工作得很好。

Nodejs 代码段

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

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  = {
    host: 'api.alchemer.com',
    path: '/v5/survey?' + reqArgs
}

console.log('Query: ', reqOptions.host + reqOptions.path);
console.log('Getting data...');
    
const req = https.request(reqOptions, resp => {
    let data = '';

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

    resp.on('error', err => {
        console.error('Error on response:');
        console.error(err);
    });

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

req.on('error', (err) => {
    console.error('Error on request:');
    console.error(err);
})

观察到的错误

Error: socket hang up
    at connResetException (internal/errors.js:607:14)
    at TLSSocket.socketOnEnd (_http_client.js:493:23)
    at TLSSocket.emit (events.js:327:22)
    at endReadableNT (internal/streams/readable.js:1327:12)
    at processTicksAndRejections (internal/process/task_queues.js:80:21) {
  code: 'ECONNRESET'
}
4

1 回答 1

1

因为你不打电话req.end()!所以它永远不会向后端发送请求。

于 2021-02-22T03:06:01.210 回答