DEV Community

Margaret W.N
Margaret W.N

Posted on • Edited on

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!

Top comments (0)