我遇到的问题是,无论何时按下“提交”按钮,我都会收到错误消息
TypeError: Cannot read property 'password' of undefined
。
我多次尝试更改请求的参数名称及其顺序,但我仍然遇到同样的错误。
这是Angular JS客户端的代码
<!DOCTYPE html>
<html>
<head>
<title>Index</title>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.5.6/angular.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>
</head>
<body ng-app="myApp">
<form ng-controller="auth" ng-submit="send()">
Username : <input ng-model="username" name="username" type="text"><br>
Password : <input ng-model="password" name="password" type="text"><br>
<button id="mybutton" type="submit">Submit</button>
</form>
<script>
var app = angular.module('myApp', []);
app.controller('auth',['$scope', '$http', function($scope, $http) {
$scope.send = function(){
var mydata = {username : $scope.username, password : $scope.password};
$http({
method : 'POST',
url : '/',
data : mydata, //{username : $scope.username, password : $scope.password}
headers: {'Content-Type': 'application/json'}
}).success(function(data, status, headers, config) {
console.log(data);
});
}
}]);
</script>
</body>
</html>
这是我的Express JS服务器的代码
var express = require('express');
var fs = require('fs');
var bodyParser = require('body-parser');
var jwt = require('jsonwebtoken');
var cors = require('cors');
var app = express();
app.use(cors());
app.use(bodyParser.urlencoded({extended : true}));
app.use(bodyParser.json());
var secret = fs.readFileSync('secret.key', 'utf8');
app.get('/', function(req, res){
res.sendFile(__dirname + '/index.html');
});
app.post('/', function(req, res){
console.log(req.body.username + ' ' + res.body.password);
if(req.body.username == 'foo' && req.body.password == 'bar')
{
var token = jwt.sign({username : 'ahmed', exp : 1440}, secret);
res.set('token', token);
res.sendFile(__dirname + '/profile.html');
}else{
res.sendFile(__dirname + '/error.html')
}
});
app.listen(8080, function(){
console.log('Shirna Tensei!');
});