2017-08-04 22 views
0

我有一个应用程序,我需要击中远程服务器来获取数据,为此我使用sample.js作为中介。但是当我运行这个文件时,我收到以下错误。“套接字挂断错误”,同时点击node.js中的远程服务器

插座挂断

我在sample.js

var qs = require('querystring'); 
var http = require('https'); 

var options = { 
    "method": "post", 
    "hostname": "xxx", 
    "port": null, 
    "path": "/xxx", 
    "headers": { 
    "authorization": "xxx", 
    "content-type": "application/x-www-form-urlencoded", 
    "cache-controller": "no-cache", 
    "postman-token": "xxx" 
    } 
}; 

var myToken = ""; 
var req = http.request(options, function(res) { 
    var chunks = []; 
    res.on("data", function(chunk) { 
    chunks.push(chunk); 
    }); 
    res.on("end", function() { 
    var body = Buffer.concat(chunks); 
    myToken = body.toString(); 
    req.write(qs.stringify({ 
     glba: 'otheruse', 
     dppa: 'none' 
    })); 
    req.end(); 
    }); 
}); 

代码我不知道这个错误的,任何人都可以请建议我帮忙吗?

回答

0

检查远程服务器是否在您的控制之下。通常情况下,这发生在服务器没有及时发送响应并且套接字刚刚结束的时候。如果发现这种情况会更好,并且使用重试/排队等。

也尝试增加选项超时。可能是服务器响应有点晚了。像这样 -

var options = { ... } 
var req = http.request(options, function(res) { 
    // Usual stuff: on(data), on(end), chunks, etc... 
}); 

req.on('socket', function (socket) { 
    socket.setTimeout(myTimeout); 
    socket.on('timeout', function() { 
     req.abort(); 
    }); 
}); 

req.on('error', function(err) { 
    if (err.code === "ECONNRESET") { 
     console.log("Timeout occurs"); 
     //specific error treatment 
    } 
    //other error treatment 
}); 

req.write('something'); 
req.end(); 

希望这有助于!

+0

嗨Aky_0788,我实际上是新的这个。可以请你解释一下'也尝试增加超时选项',以及如何增加超时..... – Niton

+0

是这样的.... setTimeout( function(){res.end()},100); – Niton

+0

编辑答案 –

相关问题