チュートリアルから、私はanglejsのボタンをクリックして私のエンドポイントに投稿するようにアプリケーションを設定しました。チュートリアルでは動作しますが、私にとってはうまくいきません。 Angular Post Requestに未定義のプロパティ 'username'を読み取ることができません
if (!(req.body.username === 'john.doe' && req.body.password === 'foobar')) {
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部分
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: '[email protected]',
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です、ログインボタンを押し経由で呼び出され
<button class="btn waves-effect waves-light" ng-click="loginUser()">Submit
<i class="material-icons right">send</i>
</button>
することができます 'はconsole.log(req.body)'を参照してください? – Rayon