HTTP Post Verb
Margaret W.N
Posted on July 21, 2020
Post allows us to add items to our database. It takes two parameters, a request and response. Syntax:
app.post((req, res) => {
return res.json( )
});
Asumming we want to add an new student to our database:
studentRouter.route('/students') // the route
.post((req, res) => {
//create a new object and pass in req.body which holds the data.
const student = new Student(req.body);
//return the data
return res.json(student);
})
req.body
does not exist so we need to extract it from the incoming request using bodyparser.
Bodyparser
Run npm install body-parser
from the terminal to install it.
Include it in our js file:
const bodyParser = require('body-parser');
Setup by adding the following code:
app.use(bodyParser.urlencoded({ extended: true}));
app.use(bodyParser.json());
Both bodyParser.urlencoded
and bodyParser.json
are middleware for parsing data. Parsing is analyzing and converting data to a format that the runtime understands. bodyParser.json
parses JSON's data. bodyParser.urlencoded
parses bodies from urls, the key value pair extended: true
allows us to choose between the query string library :false
and qs :true
library.
Saving added data to our database.
We chain a save ( ) method to our object:
studentRouter.route('/students') // the route
.post((req, res) => {
const student = new Student(req.body);
student.save();
return res.json(student);
})
We use postman to test this out, but i'm not going to dive into that.
Let's call it a day!
Posted on July 21, 2020
Join Our Newsletter. No Spam, Only the good stuff.
Sign up to receive the latest update from our blog.