Reputation: 351
I am trying to use .find() via Mongoose to GET a specific item based on its item_id (different from MongoDB assigned _id). However, nothing gets passed to the backend. The console.log(item) in my route file returns an empty object.
The item looks like this:
var item = {
item_id : "String Identifier",
desc: "String Description about item"
}
My Angular Controller:
// itemCtrl.js
App.controller('itemCtrl', function($scope, $stateParams, $http) {
$scope.item= $stateParams.itemId;
$scope.getItem = function(){
$http.get('http://localhost:3000/items/:itemId', $scope.item)
.success(function(data){
console.log("Grabbing a single item with id " + data.item_id);
$scope.item= data;
}, function(err){
console.log(err);
});
};
});
My Express backend routing:
// Item-Route.js
var express= require('express');
var mongoose = require('mongoose');
var router = express.Router();
var Item = mongoose.model('Item ');
router.get('/items/:itemId', function(req, res, next){
console.log(req.body); // returns {}
Item.find({trip_id: req.body.item_id}, function(err, item){
if(err){console.log(next(err))}
console.log(item); // returns []
res.json(item);
});
});
module.exports = router;
Can anyone spot what I am doing wrong here? Many thanks! :)
Upvotes: 1
Views: 945
Reputation: 1058
In your Express backend, I think you should get the body-parser
from npm
into the code to expose the req.body.
var app = require('express')();
var bodyParser = require('body-parser');
app.use(bodyParser.json()); // for parsing application/json
app.use(bodyParser.urlencoded({ extended: true })); // for parsing application/x-www-form-urlencoded
app.post('/profile', upload.array(), function (req, res, next) {
console.log(req.body);
res.json(req.body);
});
The above snippet should be in your main node code so that all Http request will have the same exposure.
Please refer http://expressjs.com/en/api.html in req.body
section.
Contains key-value pairs of data submitted in the request body. By default, it is undefined, and is populated when you use body-parsing middleware such as body-parser and multer.
Upvotes: 0
Reputation: 136144
As its get method you should be passed parameter in url itself like below
$http.get('http://localhost:3000/items/'+ $scope.item)
Then change server method to read parameter from URL
rather than body.
router.get('/items/:itemId', function(req, res, next){
console.log(req.body); // returns {}
Item.find({trip_id: req.itemId}, function(err, item){
if(err){console.log(next(err))}
console.log(item); // returns []
res.json(item);
});
});
Upvotes: 2