Welcome to the Treehouse Community
Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.
Looking to learn something new?
Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.
Start your free trialPat Needham
3,998 PointsQuestion json response from get request not including the text field?
I think I followed everything exactly as in the videos so far (probably missed something), but when I make the get request to localhost:3000/questions/{the question id}, everything looks fine, no errors, except the returned json doesn't have a text field.
Here is my code for the get /:qId route: router.get("/:qId", function(req, res) { res.json(req.question); });
And for the router's param method at the top of routes.js: router.param("qId", function(req, res, next, id) { Question.findById(id, function(err, doc) { if (err) return next(err); if(!doc) { err = new Error("Not Found"); err.status = 404; return next(err); } req.question = doc; return next(); }); });
And QuestionSchema inside models.js: var QuestionSchema = new Schema({ text: String, createdAt: {type: Date, default: Date.now}, answers: [AnswerSchema] });
1 Answer
Stephan L
17,821 PointsI had this same issue. The code you posted should be fine, but what's happening is the property question.text is returning undefined. You need to parse the text you're entering as json, Postman won't do it for you. This question helped get me to the solution:
(http://stackoverflow.com/questions/9177049/express-js-req-body-undefined)
With that information, I downloaded body-parser, since as the answers note, body-parser is no longer bundled with Expressjs, and then required it in my app.js file. Step by step:
-
npm install body-parser --save
- In your app.js file:
var bodyParser = require(./body-parser); app.use(bodyParser.json());
Here's the documentation for body-parser: (https://www.npmjs.com/package/body-parser)
Jonathan Ankiewicz
17,901 PointsJonathan Ankiewicz
17,901 PointsIn the video he states you wont get anything back from the get/question/:id
Have you verified the text is in the json object when you submit the post? If it's abscent there then the issue is in your post.