无法读取属性'用户名'对于Angular Post Request,共个未定义

Cannot read property 'username' of undefined for Angular Post Request

本文关键字:Request Post 未定义 Angular 读取 属性 用户 对于      更新时间:2023-10-04

在一个教程中,我设置了我的应用程序,点击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部分,通过按下按钮调用登录

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

必须使用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

根据代码中的注释:

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

该代码缺少对输入的验证。由于"username"未定义,您将收到错误Cannot read property 'username' of undefined for Angular Post Request

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

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

细化:'should probably return some sort of error code':发送一个JSON响应,其中包含错误代码404和相关的错误消息,如"未指定用户名"answers"未指定密码"

例如

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