nodejs 利用 http模块请求其他api 有时候会报错,求讨论!
发布于 5 个月前 作者 ipengyo 535 次浏览 来自 问答

原因描述: nodejs 利用 http 模块请求其他api 有时候会报错,求讨论!

报错信息

0|login_se | 2017-07-20 17:27:55.580: { Error: read ECONNRESET
0|login_se |     at exports._errnoException (util.js:953:11)
0|login_se |     at TCP.onread (net.js:563:26) code: 'ECONNRESET', errno: 'ECONNRESET', syscall: 'read' }

请求代码


function post(url, data, cb) {

    let parsed_url = parse_url(url);

    let protocal = (parsed_url.protocol == "https:") ? https : http;
    console.log('post:' + url);

    let req = protocal.request({
        host: parsed_url.hostname,
        port: parsed_url.port,
        path: parsed_url.path,
        method: 'POST',
        rejectUnauthorized: false,
        headers: {
            'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8'
    }
    }, function(res) {
        let chunks = '';
        res.setEncoding('utf8');
        res.on('data', (chunk)=>{
            chunks += chunk;
        });
        res.on('end', ()=>{
            try{
                console.log('response' + chunks);
                let response = JSON.parse(chunks);
                cb(null, response);
            } catch(e) {
                cb(e); 
            }
        });
    });

    req.on('error', function(error) {
        cb(error);
    });
    req.write(querystring.stringify(data));
    req.end();
}

线上报错log

{ Error: read ECONNRESET
2017-06-06 18:13:29.022: { Error: read ECONNRESET
2017-06-06 18:13:29.024: { Error: read ECONNRESET
2017-06-07 10:30:40.256: { Error: read ECONNRESET
2017-06-07 10:30:40.260: { Error: read ECONNRESET
2017-06-13 11:47:44.823: { Error: read ECONNRESET
2017-06-13 11:47:44.825: { Error: read ECONNRESET
2017-06-13 11:47:44.826: { Error: read ECONNRESET
2017-06-19 14:59:53.035: { Error: read ECONNRESET
2017-06-19 14:59:53.036: { Error: read ECONNRESET
2017-06-27 17:12:20.866: { Error: read ECONNRESET
2017-07-06 14:20:33.558: { Error: read ECONNRESET
2017-07-10 18:18:51.992: { Error: read ECONNRESET
2017-07-14 15:05:57.419: { Error: read ECONNRESET
2017-07-17 17:19:14.332: { Error: read ECONNRESET
2017-07-17 17:19:14.333: { Error: read ECONNRESET
2017-07-17 17:19:14.334: { Error: read ECONNRESET
2017-07-17 17:19:14.335: { Error: read ECONNRESET
2017-07-17 17:19:37.089: { Error: read ECONNRESET

1 回复

增加重试机制,控制请求的并发数

回到顶部