FunnyStunny FunnyStunny - 4 months ago 16
Node.js Question

How can i get result's body and status with jQuery

I've been developing a simple RESTful API with NodeJS and Express. When the backend was done and operative, my next step was to make HTML forms to fill the database and consume the API. I decided that using jQuery to submit the data would be a nice idea to get some practice .
So basically I want to get from a

$.post
the body and status that my app's backend generates whenever it recieves a
POST
request. Here's the form's script:

$('#addcube').submit(function(event){

//Stop the default behaviour of the submit button
event.preventDefault();

//Get the input values
var $form = $(this),
postData = {
nombre: $form.find('input[name="nombre"]').val(),
brand: $form.find('input[name="brand"]').val(),
capas: $form.find('input[name="capas"]').val(),
kind: $form.find('input[name="kind"]').val()
},

url = $form.attr('action');

$.ajax({
url: url,
type: 'post',
data: JSON.stringify(postData),
contentType: "application/json",
done: function(cube, textStatus, jqxhr){
console.log(JSON.parse(cube));
},
fail: function(jqxhr, textStatus, errorThrown){
console.log(errorThrown.msg);
}
});

});


And here's the backend route for that post:

app.post('/api/cube', cubeController.addCubo);


Which is controlled by this script:

module.exports.addCubo = function(req, res){
var Cube = require('../models/cube');
console.log('POST');
try{
console.log(req.body);

var cubo = new Cube({
nombre : req.body.nombre,
brand : req.body.brand,
capas : req.body.capas,
kind : req.body.kind
});

cubo.save(function(err){
if(!err){
console.log('Nuevo cubo guardado.');
res.send(JSON.stringify(cubo));
res.status(200);
}else{
console.log('Error al guardar: '+err);
res.send('{"status":"400","msg":"bad_request"}');
res.status(400);
}
});
}catch(err){
res.send('{"status":"500","msg":"internal_server_error"}');
}
};

Answer

No body property exists at response, use . Set $.post() type to json, or use JSON.parse() at .done(). Also, if sending error, use .fail() to log messages

  var send = $.post(url, {
    nombre : name,
    brand  : marca,
    capas  : layers,
    kind   : tipo
  }, "json"); // set expected response type to `"json"`
  // Try to get the result
  send.done(function(cube, textStatus) {
    console.log(cube, textStatus)
  });
  // handle errors
  send.fail(function(jqxhr, textStatus, errorThrown) {
    console.log(textStatus, errorThrown, errorThrown.msg)
  });