HTTP Post Verb

mtee

Margaret W.N

Posted on July 21, 2020

HTTP Post Verb

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( )
});
Enter fullscreen mode Exit fullscreen mode

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);
  })
Enter fullscreen mode Exit fullscreen mode

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');
Enter fullscreen mode Exit fullscreen mode

Setup by adding the following code:

app.use(bodyParser.urlencoded({ extended: true}));
app.use(bodyParser.json());
Enter fullscreen mode Exit fullscreen mode

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);
  })
Enter fullscreen mode Exit fullscreen mode

We use postman to test this out, but i'm not going to dive into that.

Let's call it a day!

💖 💪 🙅 🚩
mtee
Margaret W.N

Posted on July 21, 2020

Join Our Newsletter. No Spam, Only the good stuff.

Sign up to receive the latest update from our blog.

Related

Password authentication
100daysofcode Password authentication

August 11, 2020

HTTP Post Verb
100daysofcode HTTP Post Verb

July 21, 2020

Mongoose find( )
100daysofcode Mongoose find( )

July 20, 2020

Working With MongoDB
100daysofcode Working With MongoDB

July 19, 2020