无法读取Angular Post Request的undefined属性'username'

时间:2016-03-30 05:12:13

标签: javascript angularjs node.js

从教程我设置我的应用程序,点击angularjs中的按钮发布到我的终端。在教程中它可以工作,但对我来说它不起作用。

if (!(req.body.username === 'john.doe' && req.body.password === 'foobar')) { 是问题行

serverapp.js

// LOAD ---- ---- ---- ----
var fs = require('fs');
var https = require('https');

var HTTPS_PORT = process.env.PORT || 3111;
var port = process.env.PORT || 3000;

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

var router = express.Router();
var morgan = require('morgan'); // log requests to the console (express4)
var bodyParser = require('body-parser'); // pull information from HTML POST (express4)
var methodOverride = require('method-override'); // simulate DELETE and PUT (express4)


var expressJwt = require('express-jwt'); //https://npmjs.org/package/express-jwt
var secret = 'this is the secret secret secret 12356';
var jwt = require('jsonwebtoken');  //https://npmjs.org/package/node-jsonwebtoken


// We are going to protect /api routes with JWT
app.use('/api', expressJwt({
    secret: secret
}));


app.use('/', express.static(__dirname + '/'));


// if there's ever an unauth error, we redirect them
app.use(function(err, req, res, next) {
    if (err.constructor.name === 'UnauthorizedError') {
        res.status(401).send('Unauthorized :(');
    }
});


app.post('/authenticate', function (req, res) {
  //TODO validate req.body.username and req.body.password
  //if is invalid, return 401
  if (!(req.body.username === 'john.doe' && req.body.password === 'foobar')) {
    res.status(401).send('Wrong user or password');
    return;
  }

  var profile = {
    first_name: 'John',
    last_name: 'Doe',
    email: 'john@doe.com',
    id: 123
  };

  // We are sending the profile inside the token
  var token = jwt.sign(profile, secret, { expiresInMinutes: 60*5 });

  res.json({ token: token });
});


// ...MODELS, relations, rest endpoints and all that crap withheld from stack overflow

        app.get('/api/restricted', function(req, res) {
            console.log('user ' + req.body.username + ' is calling /api/restricted');
            res.json({
                name: 'foo'
            });
        });

clientapp.js

myApp.controller('userController', function ($scope, $http, $window) {
  $scope.user = {username: 'thisshouldbeempty', password: 'thisshouldbeempty'};
  $scope.isAuthenticated = false;
  $scope.welcome = '';
  $scope.message = '';

  $scope.loginUser = function () {

    $http
      .post('/authenticate', $scope.user)

      .success(function (data, status, headers, config) {
        $window.sessionStorage.token = data.token;
        $scope.isAuthenticated = true;
        var encodedProfile = data.token.split('.')[1];
        var profile = JSON.parse(url_base64_decode(encodedProfile));
        $scope.welcome = 'Welcome ' + profile.first_name + ' ' + profile.last_name;
      })
// etc....

html partial,通过按下按钮

调用登录
<button class="btn waves-effect waves-light"   ng-click="loginUser()">Submit
    <i class="material-icons right">send</i>
</button>

2 个答案:

答案 0 :(得分:1)

根据代码中的评论:

//TODO validate req.body.username and req.body.password

代码缺乏输入验证。您收到错误Cannot read property 'username' of undefined for Angular Post Request,因为&#39;用户名&#39;未定义。

您需要检查用户是否提供了邮政请求所需的输入,即

if(!req.body.username || !req.body.password)
    return; // should probably return some sort of error code

详细说明:'should probably return some sort of error code':发送带有错误代码404的JSON响应和相关的错误消息,例如&#34;未指定用户名。&#34;和&#34;未指定密码。&#34;

e.g。

if(!req.body.username) {
    res.status(404).send('No username specified');
    return;
}

if(!req.body.password) {
    res.status(404).send('No password specified');
    return;
}

答案 1 :(得分:1)

您必须使用bodyParser访问req.body:

var app = require('express')();
var bodyParser = require('body-parser');
var multer = require('multer'); // v1.0.5
var upload = multer(); // for parsing multipart/form-data

app.use(bodyParser.json()); // for parsing application/json
app.use(bodyParser.urlencoded({ extended: true })); // for parsing application/x-www-form-urlencoded

app.post('/profile', upload.array(), function (req, res, next) {
  console.log(req.body);
  res.json(req.body);
});

请参阅http://expressjs.com/en/api.html