Ajax call not getting any response - javascript

I have an Ajax call that validates an input data and show the response to the user. It usually takes less than five minutes to run and send the response, but it may vary depending on how much data I'm validating. When I run from my computer, I always get the response, but when the client runs the same application from his computer on his network, he never gets an answer. So he waits ten minutes without an answer and then press F5 to get the validation log.
I am using VueJS and below is my request.
this.$http.get(url).then(
response => {
console.log("success");
},
error => {
console.log(error);
}
)
.finally(function(){
console.log("finally");
})
.catch(function(err) {
console.log(err);
});
We're both using Chrome and looking at his console, none of the above logs are shown and there are the following errors: net::ERR_CONNECTION_RESET, net::ERR_NETWORK_CHANGED, net::INTERNET_DISCONNECTED.
Is there a way to force an answer without specifying a timeout? Are those errors above related to the problem? If so, how can I fix them?

Related

Send "Error time out" after specific amount of time in angular

I am making a API call but sometimes it is taking more time to get the response. I want to set a specific amount of time, lets say "8secs", to wait for the response if the time mention before has pass the API call should stop and show in console "ERROR time out".
I have tried adding the timeout in a pipe as other posts says like this:
`this.http.post<RefreshTokenResponseMessage>(url, tokenRequestMessage, { headers }).pipe(timeout(20)).toPromise()`
but it is showing an error with the timeout there.
I also try adding the timeout param in the header like this:
`const headers = new HttpHeaders({authorization: 'Bearer ${sessionstorage.getItem('authData')}',timeout: '${2}',});
return this.httpClient.get(URL, { headers });`
But I am also facing the same issue that it is not triggering the error.
Has anyone encounter something like this?
If you want to output a console.error if the http response has not arrived after 8 seconds, you can do this as follows:
this.http.post<RefreshTokenResponseMessage>(url, tokenRequestMessage, { headers }).pipe(
tap((res) => console.log('Result:', res)),
timeout(8000),
catchError(_ => {
console.error('ERROR time out');
return EMPTY;
})
)
.subscribe();

How to properly handle timeouts that occur during streaming, in Nodejs?

There are various posts dealing with the general issue of timeouts when using http.get(), but non of them seems to address the question of how to deal with timeouts that occur during the stream itself, after a successful response was already received.
Take this code for example. It sends a request to some server, that responds on time, but creates an artificial timeout during the stream:
(async()=>{
//Send request to a dummy server, that creates a timeout, IN THE MIDDLE OF THE STREAM.
const request =http.get('http://localhost/timeout/',async (res)=>{
const write = fs.createWriteStream('.text.txt');
try {
await pipelinePromisified(res,write);
console.log('Everything went fine')//Being that the timeout error during the stream is not caught by pipeline,
//the promise gets resolved..
} catch (error) {
//The error is NOT caught by pipeline!
console.log('Error from pipeline',error)
}
}).on('error',(e)=>{
//Error is caught here
console.log('error from request on error')
})
request.setTimeout(4000,()=>{
request.destroy(new Error('request timed out'));
//This causes the piping of the streams to stop in the middle(resulting a partial file), but the pipeline doesn't treat this is an error.
})
})()
Note the key issue: The timeout during the stream is recognized, the request is destroyed, the IncomingMessage(response) stops pumping data- but pipeline doesn't recognize it as an error.
The outcome is, that the client code is not aware of the fact that file was partially downloaded, being that no error is thrown.
How to handle this situation? In my testing, calling response.emit('error') seems to solve this, but Node's docs clearly state not to do this.
Any help would be greatly appreciated.
Update: It seems that on Node 12(i have 10 and 12 installed via nvm), an error is caught by pipeline, but not in Node 10.

Angular 10 subscribe is failing to post with error code OK(and no other errors shown)

I am new to angular 10 and I am trying to make an http post to a PHP file as shown below
this.http.post(`${environment.server}/path/file.php`, {param1, param2})
.subscribe(
data => {
console.log(JSON.stringify(data));
},
error => {
console.log(error);
this.error = error;
});
The file is successfully called and returns the following JSON as displayed in the console response
{"Email":null,"school_year":2021,"academic_year":"2021"}
When I make the request I am immediately taken to the error state and all the console log is showing below only prints "OK"
console.log(error);
The two questions are the following
Why am getting to the error when the file is successfully returning JSON
Is there a way to get a more helpful error message than just OK
You will need to set the content type to application/json
You would be better off if you used a rest API rather than using php files. .NET Core or Node.JS would give you a better development experience.
It seems that your back-end PHP send the response with status code 400. It should be revised to 200 to get the data in response. When Status code is in Error range like 400, 401, 403 ... http Response will resolved in error or catch part.
In addition if you want just get data, it's better to use GET instead of POST.

Error handling in Express JS after response

I have been trying different error handling techniques with Express. First I was just using process.on('uncaughtException'). I quickly learned that it was bad practice. After that, I tried using the new "Domain" feature in node js. I wrapped each request in a domain, however, if I would send a response and then do some more work on the server (dealing with the same request) it would not catch the errors from those functions after the response was sent. I then tried moving to the built-in error handling with Express using next(err). However, I am running into the same situation. If I send a response and then a function has an error after the response has been sent, my error handler is not called. Here is some code as an example.
async.waterfall([
function(after)
{
hashPassword(password, after);
},
function(hash, after)
{
makeToken(hash, after);
},
function(hash, token, after)
{
insertUserInfo(email, username, hash, ip, token, after);
},
function(token, id, after)
{
req.session.attempts = 0;
res.json({ err: 0, attempts: 0 }); //Response is sent
after(null, token, id);
},
function(token, id, after)
{
sendEmail(token, email, renderEmail); //Errors not caught
makeFolder(id, after); //Errors not caught
}
], function(err) {
if(err)
next(err);
}
);
As you can see from the code, I am registering a new user. Now, I could wait until I have completed all of my logic to send back the response but I thought that it would make the request appear much faster for the user if I did some of the less important things after the response has been sent. I am willing to change my code to perform everything THEN send the response, but I want to make sure that there is no solution out there that I have not tried yet.
As awesome as Express JS is, it doesn't have a time travel feature allowing you to unsend a request :) This is really the root of your problem. If your response must display the outcome, then it must wait until all the relevant actions to complete.

How to handle ajax call when there is no response from the server

I have an ajax call for some data (using jQuery). after the user clicks "submit" (and the ajax call has been sent) I am displaying a "Please wait..." message that disables everything until the request returns (so the user won't double click or click other things and mess things up).
It works great when there is any kind of error - the "Please wait..." disappears and I am displaying the user what went wrong.
But what happens if the server don't return me anything back because of communication error?
The solution I found for that is to set a timeout of 10 seconds for the "Please wait.." message that after that time it disappears and displays and error that "The communication failed". I assume that if the server didn't respond after 10 seconds then it will not respond at all - but that it false assumption.
The problem is - how can I be sure that after 20 seconds the server won't return something back? The scenario that might happen is that the user click submits --> 10 seconds later he get an error message --> 5 seconds later server response and confuses the user
How do I make sure that after I hide the "Please wait.." message nothing will pop up from the server?
when you send a request to a server. a connection is opened and its kept open unless the server responds.
1.if due to some error on the server side it cannot respond then a response code of 5xx is sent back generally (503)
2.if due to some connection issues the connection is terminated prematurely then also jquery would take that as an error.
1.so if you wanna wait for the server to send a request or connection termination (which ever occurs earlier) then u can use the completed option in the jquery ajax.
2.and if you are in a condition in which server isnt responding even after 20 secs and you think that it should have responded by now use timeout.
3.finally if your problem is that you are using some kind of customized(hand made http server) which doesn't end a request even if it encounters some error then atleast customize it enough so that it sends back some response code(because this is HTTP model of request and response)
You can handle something like this
if ( request.readyState == 4 ){ // 4 is "complete"
if ( request.status == 200 ){
// HTTP OK, carry out your normal Ajax processing
// ...
}else{
// something went wrong, report the error
error( "HTTP "+request.status+". An error was ยป
encountered: "+ request.statusText );
}
}
(or)
$.ajax({
type: "post",
url: "somepage.html",
success: function (data, text) {
//...
},
error: function (request, status, error) {
alert(request.responseText);
}
});
Generate a unique token when you fire a request,
keep a list of valid tokens,
remove tokens when the request times out/fails,
check if token is still valid before executing success/error callbacks.
The same pattern can be adapted for a situation when you need to send frequent repeating requests (e.g. autocompletion/result filtering) and only the latest one's handler should fire.

Categories