我正在尝试使用AngularJS向我的服务器发送一个相当简单的POST请求。该请求通过,命中我在后端的控制器,但由于某种原因req.data
被显示为undefined
。在AngularJS的Node.js中未定义数据POST请求
前端控制器:
function CardDirectiveController($http, $scope) {
var self = this;
self.addToFavorites = function() {
let card = {
id: $scope.$id,
attack : $scope.attack,
cost: $scope.cost,
img: $scope.img,
name: $scope.name,
class: $scope.class,
rarity: $scope.rarity,
type: $scope.type
}
return $http({
method: 'POST',
url: '/card',
data: card
})
};
}
angular.module('cardDirective').controller('CardDirectiveController', CardDirectiveController);
服务器
'use strict';
let express = require('express'),
path = require('path'),
router = require('./routes/sampleRouter'),
cardRouter = require('./routes/cardRouter');
let app = express();
// Serve any requests for static files (like index.html)
app.use(express.static(path.join(__dirname + '/public/')));
// Use any routing rules found in the router file
app.use('/', router);
app.use('/card', cardRouter)
app.listen(PORT, function() {
console.log('Application live and running on port: ' + PORT);
});
路由器:
'use strict';
let express = require('express'),
cardController = require('./../controllers/cardController');
let router = express.Router();
router.route('/').post(cardController.postCard);
router.route('/:cardName').get(cardController.showCards);
module.exports = router;
后端控制器
'use strict';
let cardController = {
showCards: showCards,
postCard: postCard
};
module.exports = cardController
function showCards(req, res) {
console.log('showCards ', req.params.cardName);
res.end()
}
function postCard(req, res) {
console.log('postCard ', req.url, req.method, req.data)
res.end()
}
我在控制台作出这一请求得到的响应是postCard/POST undefined
。控制台记录card
对象返回预期的结果。我觉得我必须缺少明显的东西,但我一直坚持了一段时间了。
请用身体解析器中间件在app.js .. '''的https:// www.npmjs.com /包/身体parser'' ' –