Angular $ http.get和Express req.body是空的
我有使用$ http.get发送数据的req.body问题。 当我在route.js方法从GET更改为POST,并在我的服务更改为$ http.post时,一切工作正常,但与GET我不能发送任何数据到我的服务器节点。 任何人有任何想法?
server.js
// modules ================================================= var express = require('express'); var app = express(); var mongoose = require('mongoose'); var bodyParser = require('body-parser'); var methodOverride = require('method-override'); var path = require('path'); // configuration =========================================== var db = require('./config/db'); var port = process.env.PORT || 8080; mongoose.connect(db.url); app.use(express.static(__dirname + '/public')); app.use(bodyParser.urlencoded({ extended: true })); app.use(bodyParser.json()); // routes ================================================== require('./app/routes')(app,__dirname); // start app =============================================== app.listen(port); console.log('Magic happens on port ' + port); exports = module.exports = app;
./app/routes.js
module.exports = function(app, __dirname) { var Card = require('./models/card'); app.post('/create', function(req, res) { var card = new Card(); card.polishWord = req.body.polishWord; card.polishDescription = req.body.polishDescription; card.englishWord = req.body.englishWord; card.englishDescription = req.body.englishDescription; card.category = req.body.category; card.save(function(err){ if(err){ res.send(err); } res.json({message: 'Card created'}); }); }); app.get('/take', function(req, res) { var condition = req.body.condition || {}; console.log(req.headers); console.log('______________'); console.log(req.body); console.log('______________'); /*TODO :: Czemu nie odbiera parametrow GET*/ Card.find(condition,function(err, cards) { if (err) res.send(err); res.json(cards); }); }); app.get('*', function(req, res) { res.sendFile('/public/index.html',{"root": __dirname}); }); };
./public/js/services/CardService(part)
cardService.getAllCards = function(){ return $http.get('/take',{params: {condition:{"category":"animal"}},data: {condition:{"category":"animal"}}}); };
req.headers
{ host: 'localhost:8080', connection: 'keep-alive', accept: 'application/json, text/plain, */*', 'user-agent': 'Mozilla/5.0 (Windows NT 6.3; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/50.0.2661.102 Safari/537.36', referer: 'http://localhost:8080/card', 'accept-encoding': 'gzip, deflate, sdch', 'accept-language': 'pl-PL,pl;q=0.8,en-US;q=0.6,en;q=0.4', cookie: '_ga=GA1.1.1073910751.1465203314' }
.package.json(依赖关系)
"dependencies": { "express": "~4.13.1", "mongoose": "4.4.20", "body-parser": "~1.15.1", "method-override": "~2.0.2" },
任何人有一个想法?
req.body
是未定义的,因为您从$http.get('/take')
发出了'GET'
请求。 你发送给服务器的是查询参数 。 查询参数的一个例子是:
http://stackoverflow.com/questions/tagged/npm?filter=all&sort=active
其中filter
和sort
分别是值为'all'
和'active'
的查询参数。
要访问Express服务器中的查询参数,您需要使用req.query
对象。 它包含查询参数及其相应的值。 '/take'
请求的req.query
对象如下所示:
{ condition: { category: "animal" } }