I am posting request with NodeJs. Here is my code:
var request = require('request');
var rp = require('request-promise');
async function sendRequest(obj){
try{ // TRY STARTS HERE
var requestTarget = await rp({
method: 'POST',
uri: obj.url,
headers: {
"accept": "*/*",
"accept-language": "en-US,en;q=0.9,ar-AE;q=0.8,ar;q=0.7",
"content-type": "application/x-www-form-urlencoded; charset=UTF-8",
"sec-ch-ua": "\" Not A;Brand\";v=\"99\", \"Chromium\";v=\"99\", \"Google Chrome\";v=\"99\"",
"sec-ch-ua-mobile": "?0",
"sec-ch-ua-platform": "\"macOS\"",
"sec-fetch-dest": "empty",
"sec-fetch-mode": "cors",
"sec-fetch-site": "same-origin",
"x-requested-with": "XMLHttpRequest",
"cookie":obj.cookie,
"Referer":obj.referer ,
"Referrer-Policy": "strict-origin-when-cross-origin"
},
timeout:16000,
body : obj.body
}).then(
(response)=>{
return response
})
// TRY ENDS HERE
}catch(error){ // catch STARTS HERE
console.error( " error is :" error);
}// catch ENDS HERE
console.log(" response is : " requestTarget);
}
Anyway, I've got Problem with request: connect ETIMEDOUT when I run the code and I have no idea how to fix it.
What could cause this error ? and how can i handle this server?
CodePudding user response:
ETIMEDOUT
means that the server didn't answer to your request in the given timeout(in your example 16 seconds) time. That error can be handled in the catch block.
CodePudding user response:
Your question title mentioned that you believe your target server is overloaded. ETIMEDOUT errors can come up in that situation. Denial of service attack?
You don't have much you can do in your code attempting the outbound connect, except catch the error, wait for a period of time and try again.
Ideally, each consecutive time you catch the error you will wait for twice as much time before trying again. For the first wait, use one second. Then wait 2, 4, 8, 16, and so forth. You want to give the target server a chance to work through its connection queue, and hammering on it slows that process.
After a minute or so you should give up. Deliver an error to your error logging system if you have one. If your service is a web service, to YOUR client deliver a 500 (generic server error), 502 (bad gateway to upstream server), or 504 (upstream server timed out), depending on what makes sense for your appication.
If you also control the target server, you can figure out what is happening there. You may need more capacity. Or a rogue client may be hitting the target really hard. It's possible your target is experiencing a denial-of-service attack.
Handling ETIMEDOUT errors is a pain in the xxx. If your service isn't mission-critical and this doesn't happen very often you can simply issue the 500, 502, or 504 error to your client. Don't forget to log the error, though: fixing the situation may require human intervention.