addyosmani / backbone-fundamentals

:book: A creative-commons book on Backbone.js for beginners and advanced users alike

Home Page:http://addyosmani.github.io/backbone-fundamentals/

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

body-parser required for reading post data in API

smurfpandey opened this issue · comments

I am going thorugh the book, and in 2nd exercise i was stuck after creating POST api route for adding new books. I was getting following error:

TypeError: Cannot read property 'title' of undefined
    at mongoose.Schema.title (E:\Pro\library-bb\dist\server.js:41:28)
    at callbacks (E:\Pro\library-bb\node_modules\express\lib\router\index.js:161:37)
    at param (E:\Pro\library-bb\node_modules\express\lib\router\index.js:135:11)
    at pass (E:\Pro\library-bb\node_modules\express\lib\router\index.js:142:5)
    at Router._dispatch (E:\Pro\library-bb\node_modules\express\lib\router\index.js:170:5)
    at Object.router (E:\Pro\library-bb\node_modules\express\lib\router\index.js:33:10)
    at next (E:\Pro\library-bb\node_modules\express\node_modules\connect\lib\proto.js:190:15)
    at Object.static (E:\Pro\library-bb\node_modules\express\node_modules\connect\lib\middleware\static.js:55:61)
    at next (E:\Pro\library-bb\node_modules\express\node_modules\connect\lib\proto.js:190:15)
    at Object.expressInit [as handle] (E:\Pro\library-bb\node_modules\express\lib\middleware.js:31:5)

It turns out we need a extra package for reading the request body. I added body-parser package, and it's working now.

new addition in package.json:

"body-parser": "*"

and changes in server.js:

Add in module dependencies

// Module dependencies.
    bodyParser = require('body-parser'); //Parser for request body in POST,PUT methods - NEW

Add just before port initialization.

app.use(bodyParser()); \\ NEW

I will open a pull-request for this issue.