1

I'm trying to post data to my REST API made with Restify via Angularjs, but when I put the data into the form and execute the submit, I get an console error provided by the server (node and restify) telling me that the field is required still when the field is filled.

Here is my post function in my server controller

    var Student = require('../models/studentSchema');

// Creating New Student
this.createStudent = function (req, res, next) {
    var student = new Student({
        name:req.body.name,
        email:req.body.email,
        age:req.body.age,
        city:req.body.city,
        pic:req.body.pic
    });


    student.save(function(err, result){
        if (err) {
            console.log('resultado: ' + result);
            console.log(err);
            return res.send({'errores':err});
        }
        else {
            return res.send({'result':result,'status':'successfully saved'});
        }
    });

};

Here is the schema

 module.exports = (function studentschema(){

  var mongoose = require('../db').mongoose;

 var schema = {
        name: {type: String, required: true},
        email: {type: String, required: true},
        age: {type: String, required: true},
        city: {type: String, required: true},
        pic: {type:String, required:true}
    };
    var collectionName = 'student';
    var studentSchema = mongoose.Schema(schema);
    var Student = mongoose.model(collectionName, studentSchema);

    return Student;

})();

My angularjs factory that makes the post using resource:

.factory('SaveStudentResource', function($resource){
return $resource('http://localhost:3000/createStudent', {}, {
    post: {method:'POST', isArray:false,  headers:{'Content-Type':'application/x-www-form-urlencoded; charset=UTF-8'}}
})

})

And the Controller that interacts with the form and try to save the json object:

    .controller('NewStudent', function($scope, SaveStudentResource){
    $scope.salut = "Hallo!";
    $scope.student = {};
    console.log($scope.student);
    $scope.saveStudent = function(){
        console.log($scope.student);
        SaveStudentResource.save({ data: $scope.student }, function(data){
            console.log($scope.student);
            console.log(data);
            $scope.student = {};
        })
    }
    console.log("Done!");
})

And the form that submits the info to the model

<form ng-submit="saveStudent()">
<div class="form-group">

    <input type="text" placeholder="Nombre" ng-model="student.name" class="form-control" required>

</div>
<div class="form-group">

    <input type="text" placeholder="Email" ng-model="student.email" class="form-control" required>

</div>
<div class="form-group">

    <input type="text" placeholder="Edad" ng-model="student.age" class="form-control" required>

</div>
<div class="form-group">

    <input type="text" placeholder="Ciudad" ng-model="student.city" class="form-control" required>

</div>
<div class="form-group">

    <input type="text" placeholder="Foto" ng-model="student.pic" class="form-control" required>

</div>
<div class="form-group">
    <button type="submit" class="btn btn-primary">Guardar</button>
</div>

I'm getting this response from server:

    m {errores: Object, $promise: d, $resolved: true}
$promise:d
$resolved:true
errores:Object
  errors:Object
    age:Object
    kind:"required"
    message:"Path `age` is required."
    name:"ValidatorError"
    path:"age"properties:Object
    __proto__:Object
city:Object
email:Object
name:Object
pic:Object
__proto__:Object
message:"student validation failed"
name:"ValidationError"
__proto__:Object
__proto__:Object

Am I missing something in my code?

Omar
  • 11
  • 1
  • 4

1 Answers1

0

I've solved it thank to the suggestion of Sarath Nair. When I print the req.body object on the server just before the save function I've watched that I've been receiving an object with the data I posted from the frontend.

 { data: 
   { name: 'Johnny Greengood',
     email: 'jg@rhead.com',
     age: '45',
     city: 'NY',
     pic: 'http://static.stereogum.com/uploads/2015/06/Jonny-Greenwood.jpg' } }

So, I noted that the main value of the object I received from req.body was 'data'. Then instead of pass the parameters to the student object, i passed 'res.body.data' and it worked as following:

  var Student = require('../models/studentSchema');

    // Creating New Student

  this.createStudent = function (req, res, next) {

    var student = new Student(req.body.data);//THIS IS THE DEAL!


    student.save(function(err, result){
        if (err) {
            console.log('resultado: ' + result);
            console.log(err);
            return res.send({'errores':err});
        }
        else {
            return res.send({'result':result,'status':'successfully saved'});
        }
    });

};

And it worked!. Does anyone knows why is happening this? Thanks!

Omar
  • 11
  • 1
  • 4
  • What are you using to parse the body in restify? – HeadCode May 09 '16 at 22:05
  • I use body parser in my app.js (server) as follows: `app.use(restify.bodyParser());` – Omar May 10 '16 at 00:31
  • If that's the case then Angular is creating that extra data wrapper. You can see for yourself by creating a bare bones restify app using bodyParser and then hitting it with curl. – HeadCode May 10 '16 at 04:46