Ajax Request always timing out - node.js

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.

Related

Angular 5 weird behavior on https calls

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?

Node, Express, Ajax, Form Submission

Help, I'm Stuck! I am playing with a CRUD setup with Node Express but with AJAX post request. I have the read form working fine.
The form has one input filed which is a lookup email. AJAX post the form data with the following code
if ($("#rsvp-search-form").length) {
$("#rsvp-search-form").validate({
rules: {
...
},
messages: {
...
},
submitHandler: function (form) {
$("#loader").css("display", "inline-block");
$.ajax({
type: "POST",
url: "/",
data: $(form).serialize(),
success: function (data, textStatus, jqXHR){
if (typeof data.redirect == 'string')
window.location = data.redirect;
}
,
error: function() {
$( "#loader").hide();
$( "#error").slideDown( "slow" );
setTimeout(function() {
$( "#error").slideUp( "slow" );
}, 5000);
}
});
return false; // required to block normal submit since you used ajax
}
});
}
I have a express post route to '/' that returns a status with res.status(#).send() and the proper success/error block is executed based on the whether status # is 400 or 200.
Now on the update form I have the same basic setup with many more form inputs, but the AJAX code does not process the res.status(#).send() response by executing the proper success or error block, instead it is just loading a new page with the same url as the request was processed from.
The AJAX code request is similar to the top with difference of url:
submitHandler: function (form) {
$("#loader").css("display", "inline-block");
$.ajax({
type: "POST",
//The website when loaded has an invitation
//object that is passed by express
url: "/rsvp/" +invitation._id,
data: $(form).serialize(),
dataType: 'application/json'
I verified that the proper post route is running and receiving the invitation._id. It returns res.staus(#).send() but the ajax does not process the success or error block it just redirects to the requesting url but does not actually render the url.
I don't know if it is just that the form is still processing the default action, if the response from express is not correct, etc etc
I hope I have been clear on my issue and someone knows what I am doing wrong here.
Regards!
Update!
I got it working. Though the url with variable was correct and express was receiving the proper id, JS was throwing an error causing everything to crash. I never caught the error because the page would reload to the blank page and clear the console. I fixed it by saving the id in a hidden field when rendering the form and used that instead. Seems to have fixed the problem.
Thanks for looking!

Node.js - How can I wait for something to be POSTed before I reply to a GET

I have 2 clients and one node.js server url - localhost:8888/ServerRequest. The First client GETs from this url and waits for 20 seconds to see if the Second client has POSTed some data for the first client within the 20 second timeout period or not.If the second client did POST before the timeout, then that value is returned to the GET request, else a default value is returned for the GET request. I am not sure what is the best way to implement this. I am trying something like this, but it is not working as desired -
function ServerRequest(response, postData , request)
{
var id;
if(request.method == "GET")
{
id= setTimeout(function( )
{
// handle timeout here
console.log("Got a timeout, sending default value");
cmd = "DefaultVal";
response.write("<?xml version=\"1.0\" encoding=\"UTF-8\"?><list id=\"20101001\"><com type=\"" + cmd + "\"></com></list>")
response.end()
},20000);
}
else if(request.method == "POST")
{
console.log("Received POST, sending POSTed value");
cmd = postData;
//Cancel Timeout
clearTimeout(id);
console.log(" \n Received POST")
response.write("<?xml version=\"1.0\" encoding=\"UTF-8\"?><list id=\"20101001\"><com type=\"" + cmd + "\"></com></list>")
response.end()
}
}
Another approach in my mind was to use 2 separate URLs - One for GET Request (/ServerRequest) and the other for POST Request (/PostData). But then how will I pass the POSTed data from one URL to the other if received before the timeout?
EDIT: I think I know now what I exactly need. I need to implement a longpoll, where a client sends a GET request, and waits for a timeout period (the data might not be immediately available to consume, so it waits for 20 seconds for some other client to POST some data for the first client to consume). In case timeout occurs, a default value is returned in response to the GET request from the first client. I'm working on the longpoll implementation I found here, I'll update if I am able to succeed in what I'm trying. If someone can point me or provide me with a better example, it will be helpful.
Edit: removed my original code after a more careful reading of the question.
The best solution would probably be websockets the browser will appear to hang waiting for 20 seconds.
Using a library like socket.io you can do this
var io = require('socket.io').listen(8888);
function postHandler(req, data, res){
io.sockets.emit("response" , data)
}
then client side
<script src="/socket.io/socket.io.js"></script>
<script>
var socket = io.connect('http://localhost:8888');
socket.on('response', function (data) {
console.log(data);
});
</script>

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

fetch data from multiple table by sending only one request

I am using node.js for server side development and backbone.js for client side development. i want to fetch data from multiple table(more than 3) by sending only one request to node.js. but i cant merge all that result with each other beacuse of asynchronous execution of node.js. i have done this but it sending a lots of get request to node js for getting data from all the tables and because of these performance of my site is become slower. please help me if anyone having any idea.
I would create a method which aggregates the results from each of the requests and sends the response back. Basically each of your three async db calls would pass their data to the same method. That method would check to see if it had all of the data it needed to complete the request, and if it did, send the response.
Here is a pseudo code example:
function handleRequest(req, res) {
var results = {};
db.getUsers(function(data) {
aggregate('users', data);
});
db.getPosts(function(data) {
aggregate('posts', data);
});
db.getComments(function(data) {
aggregate('comments', data);
});
function aggregate(name, data) {
results[name] = data;
if(results.users && results.posts && results.comments) {
res.send(results);
}
}
}
This is simplified greatly, you should also of course check for errors and timeouts to the db calls, but this will allow you to wait for all the async commands to complete before sending the data.

Resources