简体   繁体   English

Express不会将对象从服务发送到API控制器

[英]Express not sending object from Service to API controller

Trying to understand user authentication in order to integrate into my web app. 试图了解用户身份验证以便集成到我的Web应用程序中。 I've been following http://www.sitepoint.com/user-authentication-mean-stack/ as a guide. 我一直在遵循http://www.sitepoint.com/user-authentication-mean-stack/作为指南。

I'm a novice when it comes to webdev, so I'm having trouble searching the right thing to fix my problem. 我是Webdev的新手,因此在寻找正确的方法来解决问题时遇到了麻烦。 The issue is when I try to register a new user my object isn't getting received in my api controller. 问题是当我尝试注册新用户时,我的对象未在我的api控制器中收到。

register.controller.js register.controller.js

(function () {
  angular
  .module('misplaced')
  .controller('registerCtrl', registerCtrl);

  registerCtrl.$inject = ['$location', 'authentication'];
  function registerCtrl($location, authentication) {
    var vm = this;
    vm.onSubmit = function () {
    authentication
      .register(vm.credentials)
      .error(function(err){
        alert(err);
      })
      .then(function(){
        $location.path('profile');
      });
  };

authentication.service.js authentication.service.js

(function () {
 angular
 .module('misplaced')
 .service('authentication', authentication);

 authentication.$inject = ['$http', '$window'];
 function authentication ($http, $window) {
   register = function(user) {
   return $http.post('/api/register', user).success(function(data){
     saveToken(data.token);
   });
 };

authentication.js authentication.js

module.exports.register = function(req, res) {

  var user = new User();
  user.name = req.body.name;
  user.email = req.body.email;
  user.setPassword(req.body.password);

  user.save(function(err) {
    var token;
    token = user.generateJwt();
    res.status(200);
    res.json({
      "token" : token
    });
  });
};

Through some console.log I've tracked that the object gets created fine from the register.controller and gets passed to authentication.service fine, but when I try to console.log the object in authentication.js file it's empty. 通过一些console.log,我已经跟踪到从register.controller可以很好地创建该对象,并可以将其传递给authentication.service,但是当我尝试在authentication.js文件中进行console.log时,该对象为空。 Can someone help explain to me what might be happening? 有人可以帮我解释一下会发生什么吗? Thanks in advance! 提前致谢!

This sounds like an Express configuration issue, you may not be using the bodyParser module in Express. 这听起来像Express的配置问题,您可能没有在Express中使用bodyParser模块。

var bodyParser = require('body-parser');
var app = express();

app.use(bodyParser.json());

This will allow your middleware to access the request body properties in req.body 这将允许您的中间件访问req.body的请求主体属性。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM