I am trying to build REST API with NodeJS and Express. I create routes for offers
and when I try to send GET request I get empty response with 200 status code
routes.js
router.get('', passport.authenticate('jwt', { session: true}), OfferController.getOffers);
offerController.js
exports.getOffers = function(req, res) {
Offer.find({}, function(err, task) {
if (err){
return res.send(err);
}
res.json(Offer);
});
}
what is missing here?
What about:
exports.getOffers = function(req, res) {
Offer.find({}, function(err, task) {
if (err){
return res.send(err);
}
// Change this line from res.json(Offer) to:
res.json(task);
});
}
The result of Offer.find()
is in task variable, that's what you want to send back to client.
Offer
is a mongoose model you can not send it back. And you don't need to return it because it is async.
Use this structure:
exports.getOffers = function(req, res) {
Offer.find({}, function(error, result) {
var myRes = {};
if(error){
myRes.error = error;
myRes.error.message = "Error..."
}else{
myRes.data = result;
}
res.send(myRes);
});
}
Why are you sending Offer
?
You should be sending the output of Offer.find({})
ie task
.
So, res.send(task)
should be the statement after your error condition. It would look something like:
exports.getOffers = function(req, res) {
Offer.find({}, function(err, task) {
if (err){
return res.send(err);
}
res.json(task); //this
});
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.