Reputation: 83
Got a registration form with ajax script, POSTing to nodejs backend. The problem is that ajax request is hanging for up to 30-60 seconds before executing "error" or (sometimes!) "success" events. If timeout is set, error is fired after 3 secs. Node backend writes the results to console immediately. Is something wrong with ajax or backend?
HTML:
<form id="add" action="" class="col-md-3">
<div class="form-group">
<label class="input">username</label>
<input type="text" name="username" id="username">
</div>
<div class="form-group">
<label class="input">pass</label>
<input type="password" name="pass" id="pass" class="">
</div>
<div class="form-group">
<input type="hidden" name="new" value="new" id="new">
<input type="hidden" name="role" value="admin" id="role">
</div>
<div id="submit" class="btn">Add</div>
JQuery:
$(function () {
$('#submit').on('click', function() {
var form = $('#add');
var data = {"username":$('#username').val(), "password": $('#pass').val() , "role": $('#role').val(), "new": $('#new').val()}
alert ('ajax start: ' + JSON.stringify(data));
$.ajax({
url: '/add',
type: 'POST',
data: data,
// timeout : 3000,
success: function(responseText, statusText, xhr) {
console.log("Worked!" + responseText);
alert ('success');
},
complete: function() {
alert ('complete');
},
error: function(err) {
console.log('err:');
console.log(err);
alert ('err: ' + err.statusCode() + " " + err.statusText);
}
});
});
});
route to process the request:
module.exports = function(req, res) {
if (req.body.hasOwnProperty("new")){
//add new user
console.log('new');
var Auth = app.locals.Auth;
Auth.register(req, function (err){
console.log('ended registration');
if (err){
console.log('err: ' + err + res);
res.json({"err":err});
}else{
console.log('successfully registered');
res.json({"success":'success'});
}
console.log('res.end');
res.end();
console.log('return');
return ;
});
Upvotes: 0
Views: 1238
Reputation: 83
The problem was in route code:
res.end();
just needed to remove this row
Upvotes: 1
Reputation: 19578
It seems the okay code to me. Actually only change I could suggest you is to add an error code as well as success code to your response.
Success: res.json(200, {"success": "success"});
Error: res.json(400, {"error": err});
Upvotes: 0