2017-08-04 24 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

編輯答案 –

相關問題