Create your REST API with Express (3/3)

October 14, 2018

You are reading the third part of Create Rest API with Express, feel free to read Part 1 and Part 2 In this part, I will send a request to the POST method using Vue.

Add form to send data.

The first step is to include the CDN to index.html for a little styling. The HTML contains a form with input and textarea element linked to Vue. We use v-model and the v-on directive to liest to form submit.

<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.1.3/css/bootstrap.min.css"> <title>Document</title> 
</head>
 <body> 
 <div id="app" class="container"> 
 <div class="row"> 
 <form v-on:submit="sendToApi"> <div class="form-group"> <label for="title">Title</label> <input id="title" v-model="title" class="form-control" type="text"> </div> <div class="form-group"> <label for="description">Description</label> <textarea id="description" class="form-control" ></textarea> </div> <input class="btn btn-primary" type="submit" value="Send to API"> </form> </div>`

The method sendToApi() will send the data from our app to the API.

Using the preventDefault to stop the submit and create a new object model with the values from Vue properties title and description with the axios post method and passing the endpoint url and the object.

sendToApi(event){ 
    event.preventDefault(); 
    let model = { 
        title: this.title, 
        description: this.description
         }; 
         let apidocument = this.apiurl + 'documents/' 
         axios.post(apidocument, model)
         .then(function(r) { console.log(r); }) 
         },`

Install body-parse and setup middleware.

body-parse is a node package which allows extracting incoming request data and attaches this as a new field to the request, go to the terminal and run this:

npm install body-parser -s

I will configure express to use body-parser edit app.js and import body-parser.

const bodyparser = require("body-parser");

Now I also need to use it add it as an extra middleware, into app.use and send bodyparser.json() and also bodyparser.urlencoded does it parse my url encoded data.

app.use(bodyparser.json()); 
app.use(bodyparser.urlencoded({extended: false}));

Create the route to get the post and read the body

I create a post method and using req.body thanks to body-parser I can read the data sent from the client.

app.post("/api/documents",(req, res, next) => { 
    const post = req.body; console.log(post); 
    console.log("posted data") 
    res.status(201).json( 
        { message: 'document created' }
        ); 
        })

It’s Done! your nodemon will relaunch the API and will send the post from our Vue page,click into send data you can see the message from our API.

[nodemon] restarting due to changes... 
[nodemon] starting node backend/app.js server is running. { title: '', description: '' } posted data { title: 'the title of app', description: '' }`