我是一个MEAN堆栈newb遇到路由问题,并且可能解析:以下代码给我一个req.body:undefined。:
Server.js:
var express = require('express');
var app = express();
var bodyParser = require('body-parser');
var mongoose = require('mongoose');
var db = mongoose.connect('mongodb://127.0.0.1/roomem');
var Roomie = require('./public/models/roomie.server.model');
app.use(bodyParser.json());
var roomieRoutes = require('./public/routes/roomie.server.routes');
roomieRoutes(app);
module.exports = app;
app.listen('3000');
Controller.js:
roomem.controller('roomieCtrl', ['$scope', '$http', '$location', '$log', function($scope, $http, $location, $log)
{
$scope.login = function()
{
console.log($scope.person.meta); // This outputs the object correctly
$http.get('/roomielogin',$scope.person.meta).success(function(response)
{
console.log(response); // This returns null
});
}
}]);
roomie.server.route.js:
module.exports = function(app)
{
app.get('/roomielogin', function(req,res)
{
console.log(req.body); // displays undefined
console.log(req.headers); // shows that the document can be json
var name = req.body.username;
var query = Roomie.where({ 'meta.username': name });
query.findOne(function(err, doc) {
if (err) return console.error(err);
console.log(doc);
res.json(doc);
});
});
}
我已经尝试过几乎所有内容并阅读有关此内容的每篇文章。大多数时候,人们只是放置他们的app.use(bodyParser.json());他们的剧本太晚了,但是我似乎在正确的地方。所有其他查询都正常。这是唯一有问题的问题。我感谢任何帮助。
答案 0 :(得分:0)
如果要在正文中发送数据,则需要执行
GET
POST
请求。
改变 -
$http.get('/roomielogin',$scope.person.meta)
要
$http.post('/roomielogin',$scope.person.meta)
<强>&安培; 强>
app.get('/roomielogin', function(req,res)
要
app.post('/roomielogin', function(req,res)