req.body是未定义的平均应用程序

时间:2016-11-24 16:00:53

标签: javascript angularjs node.js mongodb express

我的应用有问题。告诉你问题是什么的简单方法让我告诉你我的代码

var Meetup = require('./models/meetup');



module.exports.create = function (req, res) {
  var meetup = new Meetup(req.body);
  console.log(req.body);
  meetup.save(function (err, result) {
    console.log(result);
    res.json(result);
  });
}

module.exports.list = function (req, res) {
  Meetup.find({}, function (err, results) {
    res.json(results);
  });
}

console.log(req.body);输出未定义  console.log(result);在输出{ __v: 0, _id: 5836ce6c38485021ec195a82 }

时输出{ __v: 0,name:'text input' _id: 5836ce6c38485021ec195a82 }

这是我的角度控制器:

myApp.controller('meetupsController', ['$scope', '$resource', function ($scope, $resource) {
  var Meetup = $resource('/api/meetups');
$scope.meetups = []

  Meetup.query(function (results) {
    $scope.meetups = results;
  });


  $scope.createMeetup = function () {
    var meetup = new Meetup();
    meetup.name = $scope.meetupName;
    meetup.$save(function (result) {
      $scope.meetups.push(result);
      $scope.meetupName = '';
    });
  }
}]);

我的模特:

var mongoose = require('mongoose');
var Schema = mongoose.Schema;

var Meetup = new Schema({
  name: String,
  text:String,

});


module.exports = mongoose.model('Meetup', Meetup);

感谢您的帮助。 PS我使用bodyparser

1 个答案:

答案 0 :(得分:0)

如果req.body未定义,则需要:

  • 确保使用后端的body-parser
  • 确保您在前端传递正确的数据
  • 确保您的前端传递的数据位于正确的位置(正文)
  • 确保数据格式正确(JSON?URL编码?)
  • 在浏览器的开发者控制台中打开“网络”标签,查看已转移的内容

有关详细信息,请参阅您自己问题的答案之一: