Welcome to Part 3 of this review of the Pluralsight course RESTful Web Services with Node.js and Express by Jonathan Mills.
Node.js and Express gives us the ability to write lightweight, fast, scalable APIs quickly.
Also in this series:
Part 1 – What is REST?
Part 2 – Getting Data
Part 3 – Posting Data
Part 4 – Updating Data
Part 5 – Testing
In app.js we implement the .post method.
In order to get access to the post data we use a body parser, which is a piece of Express middleware that reads the body and parses it into a JSON object.
npm install body-parser –save
We see a couple of app.use statements that we need to write for bodyParser.
Our post method looks at the body, see if it has any JSON objects in it, and if so it adds any to req.body
We end by typing gulp to run our server
Testing with Postman
Postman is a Chrome extension for test web API calls. It is a lot like Fiddler, but I find it a little easier to use for some tasks.
Jonathan uses Postman for testing here, doing GET requests first and we see that we get our list of books back okay, and we also get back only one when we add our Id.
Next some POST requests. This requires a header to be added:
We also submit the title, genre and author as JSON in the body of the request.
In this demo we update app.js to save our book data to MongoDB, and we see it working using Postman.
There’s already 66 lines of code in app.js
We create Routes/bookRoutes.js and pull in a reference to Express.
Then we create a routes function.
Injecting Our Model
When we test in Postman we see an error in bookRoutes.js: “ReferenceError: Book is not defined”
To fix this we inject our Book model into bookRoutes. This is done by passing in Book in round brackets at the end of our require statement:
bookRouter = require(./Routes/bookRoutes’)(Book)
Part 4 – Updating Data is coming soon