Angular 5 weird behavior on https calls - node.js

We are using angular 5 and nodejs for our application and we are facing a weird behavior in our production.We are sending a request call using httpclient from angular and when it gets a delayed response, it starts to retry the request in every 2 minutes as a default behavior.Once the request gets the response,it stops retrying the request.We are having a subscribe method inside another subscribe.
this._inspectionPageService.transferCheck(this.org)
.subscribe(status => {
if (status === true){
this._inspectionPageService.saveReceipts(this.genId, this.receiptData)
.subscribe(results => {
this.receiptInfo = results;
});
} else {
this._sharedServices.throwMessage('error', 'Failed.Please try Again');
}
});
Here saveReceipts call is taking more than 2 minutes to complete the request.
We are not using any retry method.Our interceptors also do not have any retry methods.This occurs strangely.
When we checked the log,we found the multiple entries in the difference of two minutes.We tried to replicate this issue in test instance,but unable to reproduce it.
Does anybody have idea on this?

Related

Why would my server make a proxy request to the same put function from two different pages and only work on one?

I am getting a proxy error from a PUT action only when its called from a certain page. When I call it from a different page, it works fine.
My code is that doesn't work is:
const startedWorkout = () => {
if (workout?.exercises && selectedWorkout) {
if (selectedWorkout.started && selectedWorkout.completed) {
// restarts workout session
dispatch(toggleWorkoutIncomplete(selectedWorkout));
}
dispatch(startWorkout(selectedWorkout));
dispatch(startExercise(selectedWorkout, workout.exercises));
}
};
When my frontend's URL is http://localhost:8101/workout-started/WKsp5Odze1WuAGm6txWx
All 3 of those functions get the same error:
Proxy error: Could not proxy request /workout/WKsp5Odze1WuAGm6txWx from localhost:8101 to https://us-central1-traineraid-283616.cloudfunctions.net/api.
[react-scripts] See https://nodejs.org/api/errors.html#errors_common_system_errors for more information (ECONNRESET).
This is the request for each of the function calls:
axios.put(`workout/${workoutId}`, newValues)
I call the exact same functions that use the PUT request above from a different URL: http://localhost:8101/workouts/list
and it works fine.
I have never seen an error so specific and I have no idea where to start looking for a backend call that doesn't work on specific frontend URLs.
Let me know if i am missing something obvious. I tried to cut down on the code because it would be a lot of stuff to have to copy here but I can post here at any request for more info.
I solved it myself. It turned out that I was navigating to the next page before the functions could load.
I removed the href from the button and changed the code from the onclick function to:
const startedWorkout = () => {
if (workout?.exercises && selectedWorkout) {
if (selectedWorkout.started && selectedWorkout.completed) {
// restarts workout session
dispatch(toggleWorkoutIncomplete(selectedWorkout));
}
dispatch(startWorkout(selectedWorkout));
dispatch(startExercise(selectedWorkout, workout.exercises));
props.history.push(`/workout-started/${workout?.id}`)
}
};

Chain of endpoints in Node and Express: how to prevent that some of them stops all the series?

In some page I have to get information from 8 different endpoints. 2 of them are outside of my application and sometimes they cause an delay at displaying data. The web browser waits until the data is processed. Once they're outside of my app I can't refactor them in order to make them fast, but I need to show the information that they provide. In addition, sometimes one of them returns nothing. If so, I use default data to show to the user. The waiting time takes time for the user experience perspective.
I'm using promises to call these endpoints. Below is part of the code snippet that I am using.
The code is working fine. The issue is the delay.
First. Here is the array that contains all the service that I need to process:
var requests = [{
// 0
url: urlLocalApi + '/endpointURL_1/',
headers: {
'headers': 'apitoken'
},
}, {
// 1
url: urlLocalApi + '/endpointURL_2/',
headers: {
'headers': 'apitoken'
},
];
The code of array is encapsulated in this method:
const requests = homePageFunctions.createRequest();
Now, it is how the data is processed. I am using both 'request-promise' and 'bluebird', and a personal logger to check it out if everything goes fine.
const Promise = require("bluebird");
const request = require('request-promise');
var viewsHelper = {
getPageData: function (requests) {
return Promise.map(requests, function (obj) {
return request(obj).then(function (body) {
AppLogger.log(`Endpoint parsed`, statusLogger.infodate);
return JSON.parse(body);
});
});
}
}
module.exports = viewsHelper;
How do I call this?
viewsHelper.getPageData(requests)
.then(results => {
var output = [];
for (var i = 0; i < results.length; i++) {
output.push(results[i]);
}
// render data
res.render('homepage/index', output);
AppLogger.log(`PageData is rendered`, statusLogger.infodate);
})
.catch(err => {
console.log(err);
});
};
Take a look that inside of each index item of "output" array, there is the output of each data of each endpoint.
The problem here is:
If any of the endpoint takes long, the entire chain slows even though
if they are already processed. The web page waits in a blank mode.
How to prevent this behavior?
That is an interesting question but I have questions in order to answer it effectively.
You have Node server and client (HTML/JS)
You have 8 end points 2 are slow because you don’t have control over them.
Does the client (page) aware of the 8 end points? I .e you make 8 calls everytime you reload the page?
OR
Does the page makes one request to your node JS and your nodeJS synchronously calls the 8 end points
If it is 1 then lazy loading will work easily for you since the page is making the requests.
If it is 2 lazy loading will work only at the server side however the client will be blocked because it doesn’t know (or care how you load your data. The page made one request and it is blocked waiting for that request..
Obviously each method has pros and cons ..
One way you can solve this is to asynchronously call those end points on node and cache them and when the page makes the 1 request you have the data ready ..
Again we know very little about the situation there are many ways to solve this
Hope this helps

Ajax Request always timing out

I am making a food ordering website in which i have to send all the order details from ejs page to the node backend. My code is shown below. The problem i am having with this is that the ajax request is always timing out irrespective of the timeout time being 10 seconds to one minute(no data is being transferred and its timing out at the given time).
$.ajax({url:"/checkout",
timeout:10000,
type:"POST",
data:{
restro:b,
custo:a,
loc:c,
bill:bill,
order:arr,
slot:e,
pay:f,
room:g},
success:(result)=>{
console.log(result+" its here");
},
error:(x,y,error)=>{console.log(error)}});
the nodejs code working in the backend is:-
app.post("/checkout",isLoggedIn,(req,res)=>{
for(var i=0;i<req.body.order.length;i++){
if(req.body.order[i].itname=="nullified")
req.body.order.splice(i,1);
i=0;
}
var orderpp={
restroname:req.body.restro,
cusname:req.body.custo,
deliveryadd:req.body.loc,
bill:req.body.bill,
items:req.body.order,
deliveryslot:req.body.slot,
payment:req.body.pay,
roomdet:req.body.room
};
console.log(orderpp.items);
Order.create(orderpp,(err,neworder)=>{
if (err) {
req.flash("error",err.message);
res.redirect("/index");
} else {
console.log(neworder);
}
})
})
Expected output is a new record to be created and displayed in the server console but the ajax request is timing out. Please help me out with this.
Do you see a timeout on client side ?
If so, I don't see a res.send(status_code, res_object) or res.json(res_object) in case order creation was a success, it is essential to send back a response and mark request as completed.

Request Timeout while uploading image

Am developing web application using golang for web server and frontend with reactJS and nodeJS to serve the frontend. I have two issue while uploading images that are big (currently am testing with 2.9 mb) the first one am getting is a timeout within 10 second saying request timeout at the browser side but the upload is successfully uploaded to the database. The second issue is the request is being duplicated two times and as a result the request is saved to the database two times. I have searched on stack overflow but it doesn't seem to work.
First Option
Here is the code using ajax call i.e. fetch from isomorphic-fetch
Following suggestion to implement a timeout wrapper at https://github.com/github/fetch/issues/175
static addEvent(events){
let config = {
method: 'POST',
body: events
};
function timeout(ms, promise) {
return new Promise(function(resolve, reject) {
setTimeout(function() {
reject(new Error("timeout"))
}, ms)
promise.then(resolve, reject)
})
}
return timeout(120000,fetch(`${SERVER_HOSTNAME}:${SERVER_PORT}/event`, config))
.then(function(response){
if(response.status >= 400){
return {
"error":"Bad Response from Server"
};
}else if(response.ok){
browserHistory.push({
pathname: '/events'
});
}
});
}
The request timeout still occurs within 10 seconds.
Second Option
I have tried a different node module for the ajax call i.e. axios since it has a timeout option but this also didn't fix the timeout issue.
Third Option
I tried to set read timeout and write timeout on the server side similiar to https://blog.cloudflare.com/the-complete-guide-to-golang-net-http-timeouts/
server := &http.Server{
Addr: ":9292",
Handler: router,
ReadTimeout: 180 * time.Second,
WriteTimeout: 180 * time.Second,
}
Again am getting request timeout at browser side within 10 seconds.
what shall I do to fix or point me if i made a mistake ?

Sometimes not receiving success or error response when saving Backbone model

When saving a model to a Node.js endpoint I'm not getting a success or error response every time, particularly on the first the first save and then sometimes on other attempts. The Node.js server is sending a success response every time, and if I use a Chrome rest client it works every time.
var mailchimpModel = new MailchimpModel();
var data = {
"email": $('#email').val()
}
mailchimpModel.save(data, {
success: function(model, response) {
console.log("success");
console.log(response);
},
error: function(model, response) {
console.log("error");
}
});
What I have found is the nodejs server is receiving 2 requests when it's failing
OPTIONS /api/mailchimp 200
POST /api/mailchimp 200
and I only get a success response if I submit the request again straight afterwards.
It's possible your model is failing client-side validation. To check, try:
console.log(mailchimpModel.save(data));
If the value is false then your model is failing client-side validation (usually defined in a validate function in the model). You can check the errors with
console.log(mailchimpModel.valdiationError);
OK found that i need to handle the OPTIONS method on the server, using the soltion on this post worked for me.
https://stackoverflow.com/a/13148080/10644

Resources