【问题标题】:I'm getting "Path 'name_of_the_field' is required" when post to my restify API发布到我的 restify API 时,我收到“需要路径 'name_of_the_field'”
【发布时间】:2016-05-09 22:47:31
【问题描述】:

我正在尝试通过 Angularjs 将数据发布到使用 Restify 制作的 REST API,但是当我将数据放入表单并执行提交时,我收到服务器(节点和 restify)提供的控制台错误告诉我填写该字段时,该字段仍然是必需的。

这是我的服务器控制器中的 post 函数

    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'});
        }
    });

};

这是架构

 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;

})();

我使用资源发布帖子的 angularjs 工厂:

.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'}}
})

})

以及与表单交互并尝试保存json对象的Controller:

    .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!");
})

以及向模型提交信息的表单

<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>

我收到了来自服务器的响应:

    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

我的代码中是否缺少某些内容?

【问题讨论】:

  • 你能从服务器代码中打印出 req.body 的输出吗?
  • 舒尔,当我将 console.log 设置为 req.body 时,我得到一个数组,其中包含我要发布的表单的数据。

标签: angularjs node.js mongodb mean restify


【解决方案1】:

感谢 Sarath Nair 的建议,我已经解决了。当我在保存功能之前在服务器上打印 req.body 对象时,我看到我已经收到了一个带有我从前端发布的数据的对象。

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

所以,我注意到我从 req.body 收到的对象的主要值是“数据”。然后,我没有将参数传递给学生对象,而是传递了“res.body.data”,它的工作原理如下:

  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'});
        }
    });

};

它成功了!有谁知道为什么会这样? 谢谢!

【讨论】:

  • 你用什么来解析restify中的body?
  • 我在我的 app.js(服务器)中使用 body 解析器,如下所示:app.use(restify.bodyParser());
  • 如果是这样,那么 Angular 正在创建额外的数据包装器。您可以通过使用 bodyParser 创建一个简单的 restify 应用程序,然后使用 curl 来访问它。
猜你喜欢
  • 2020-01-10
  • 2019-08-25
  • 1970-01-01
  • 2019-09-21
  • 1970-01-01
  • 1970-01-01
  • 2017-03-05
  • 2021-07-10
  • 2021-08-05
相关资源
最近更新 更多