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 the 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.



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' }); })

Done! your nodemon will relaunch your API is ready to get the post from our Vue page, if you fill the form and 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: '' }

#express #vuejs

Originally published at danywalls.com on October 14, 2018.

Dany Paredes

Hi, I'm Dany Paredes, few years ago I was working with .NET, but in my last years I have been focusing in Javascript using Vue , Angular or React. You can read more in Twitter or Github.