我正在尝试使用AngularJS向我的服务器发送一个相当简单的POST请求。该请求会通过并在后端点击我的控制器,但出于某种原因,req.data
显示为undefined
。
前端控制器:
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
对象返回预期结果。我觉得我必须错过一些明显的东西,但我已经被困了一段时间了。
答案 0 :(得分:2)
您需要使用bodyParser
中间件来解析请求正文。
安装body-parser
模块:
$ npm install body-parser
在app.js中配置它:
var bodyParser = require('body-parser');
// parse application/json
app.use(bodyParser.json());
在您的控制器中使用req.body
代替req.data
:
function postCard(req, res) {
console.log('postCard ', req.url, req.method, req.body);
res.end();
}
答案 1 :(得分:0)
请在app.js文件中使用body-parser。 将server.js文件更改为以下代码
'use strict';
let express = require('express'),
path = require('path'),
router = require('./routes/sampleRouter'),
cardRouter = require('./routes/cardRouter'),
bodyParser = require('body-parser');
let app = express();
// Serve any requests for static files (like index.html)
app.use(express.static(path.join(__dirname + '/public/')));
// parse application/json
app.use(bodyParser.json());
// 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);
});