|

Vue.js Express Tutorial

MEVN Tutorial

In this tutorial we are going to build a small project using the MEVN stack. MEVN is the acronym for MongoDB, Express, VueJS, and Node.js as the full stack application. MongoDB is our data storage mechanism, Express is the middleware to handle HTTP requests and routing, VueJS is the client side JavaScript to render data, and Node.js is the server our application will run on. As an added bonus, we’ll include a cool Bootswatch theme to make the CSS look good. Let’s get started.


Create Directory and run npm init

To get started, we’ll add a new directory to hold our server code and run an npm init -y to initialize a package.json file for us.

node $mkdir MEVN-Tutorial
node $cd MEVN-Tutorial
MEVN-Tutorial $npm init -y
Wrote to C:\node\MEVN-Tutorial\package.json:
{
  "name": "MEVN-Tutorial",  "version": "1.0.0",
  "description": "",
  "main": "index.js",
  "scripts": {
    "test": "echo \"Error: no test specified\" && exit 1"
  },
  "keywords": [],
  "author": "",
  "license": "ISC"
}

Add Dependencies to the project

Now we can add all of the dependencies we’ll be using in this project. We will add express, morgan, cors, and body-parser to start. Express is used to create the API, morgan is used to log http requests to the console, cors allows the client to talk to the front end, and body-parser is what is used to allow the back-end to read the data sent from the front end.

MEVN-Tutorial $npm install express morgan cors body-parser
npm notice created a lockfile as package-lock.json. You should commit this file.npm WARN MEVN-Tutorial@1.0.0 No description
npm WARN MEVN-Tutorial@1.0.0 No repository field.
+ express@4.16.3
+ body-parser@1.18.3
+ morgan@1.9.0
+ cors@2.8.4
added 63 packages from 50 contributors and audited 161 packages in 4.205s
found 0 vulnerabilities

Add an index.js file

Let’s add an index.js file to our project as this will be the entry point into the application.

MEVN-Tutorial $touch index.js

MEVN Project Skeleton


Test Out Our Server

We have everything in place to test out our server. We just need to add a little bit of code to make it work.
index.js

Now we can run the project like so.

MEVN-Tutorial $node index.js
listening on 4000

If we load up http://localhost:4000/ in our browser, we can see the server is working. Great!
the server is working json response


Create Client The Client Directory

We’re going to be using Vue.js on the client side, so let’s go ahead and start setting that up now. First we’ll install the Vue Cli.

MEVN-Tutorial $npm i @vue/cli

Once that is complete, let’s run the vue create client command and choosing the Router and Linter / Formatter options.
vue cli 3 manual presets
vue cli step 2
vue cli step 3
vue cli step 4
vue cli step 5

When you finish going through all of the prompts, you should see something like the following. Basically, we are now building the front end to our back end api within the client folder using Vue cli.

✨  Creating project in C:\node\MEVN-Tutorial\client.
🗃  Initializing git repository...
⚙  Installing CLI plugins. This might take a while...


> yorkie@2.0.0 install C:\node\MEVN-Tutorial\client\node_modules\yorkie
> node bin/install.js

setting up Git hooks
done

added 1081 packages from 734 contributors and audited 10674 packages in 101.129sfound 0 vulnerabilities

🚀  Invoking generators...
📦  Installing additional dependencies...

added 109 packages from 43 contributors and audited 12463 packages in 41.475s
found 0 vulnerabilities

⚓  Running completion hooks...

📄  Generating README.md...

🎉  Successfully created project client.
👉  Get started with the following commands:

 $ cd client
 $ npm run serve

Wow! Pretty cool that Vue cli is! Ok, we since it says we can run those two commands, we will do that and then visit http://localhost:8080/#/ to see our Vue installation running.
vue cli 3 npm run serve

Now just to change things up, we’ll include the CSS for the Bootswatch Sketchy theme by adding it to index.html like we see here.
bootswatch sketch css include

Now when we look at our front end, check out the cool effect!
vue bootswatch

Excellent. We now have a front end that will consume the API which we are still building. In fact, let’s shift back to the back-end code and continue building out what is needed.


Connecting To MongoDB With Monk

In a different tutorial we used Mongoose to connect to our MongoDB server. In this episode, we’ll make use of Monk, which is a lighter package for quick use. So let’s install Monk now and while we are at it, we can install Joi as well for some simple data validation.

MEVN-Tutorial $npm i monk joi

Create a message model

Right then. We are ready to create a model to store messages that a user might submit to our api. In our project, we can add a db directory and then place connection.js and messages.js files in there.

MEVN-Tutorial $mkdir db
MEVN-Tutorial $cd db
db $touch connection.jsdb $touch messages.js

connection.js
In the connection.js file, we can add this code which will allow us to connect to MongoDB.

messages.js
This is the model for working with messages.


Add a route to get messages from Mongodb

In index.js, we can add this code.

We can even test this now. In a command prompt, we can run mongod to kick off our Mongo server. Then, we will need to run node index.js to launch our project. At that point, if we visit http://localhost:4000/messages, we are getting back an empty array. This is good actually, because it means that we are talking to the Mongo database, we just don’t have any messages in there quite yet.


Add a route to create a message

In index.js, let’s add a route to handle a POST request to the API which will add a new message to the database.


POST to API using Postman

What we can do now is to send a POST request to the API using Postman.
post request via postman

Now let’s use Compass to see if the data is in the database. Looks good!
new message in mongodb

In addition, if we visit http://localhost:4000/messages, we now see the message which is stored in the database returned in JSON format.
json response from mevn stack


Consume API and Display Messages With Vue

Our API is now working. It is able to accept and return messages in JSON format. Now we want to render one or more messages on the screen using our Vue Client. We can start by adding the following Vue code to Home.vue.

To test this now we actually need to node instances running. In the MEVN-Tutorial directory we must run node index.js to fire up our API server. Then, we must also launch our client by opening a *different* command prompt and running npm run serve from the client directory. Hopefully that makes sense! Once that is complete we will have two instances running.

http://localhost:4000/messages will be providing the backend API.
http://localhost:8080/#/ will be providing our client service.

Ok, with both of these running, and our Home.vue file populated with some Vue markup – we can see that our data is being rendered on the page. Slick!
vue client rendering api data

This is pretty cool. Our browser is making a GET request to an Express server, which then in turn responds with JSON data from a MongoDB database. At that point, our Vue.js code consumes that JSON data, and renders it out onto the page. Excellent!


Add a Vue Form To Submit New Messages

Now we can add this code to Home.vue so that we have a form to add a new message.

Let’s go ahead and manually fill out the form with some new data for a message and test it out.
vuejs form post request to api

Once we click on submit, the POST request is sent to our API – along with the data we entered into the form. Now we see the new message on the page. Great!
new message is displayed

Let’s add one more message to make sure things are working.
second example of vue post to API

Once again, we see the new message on the page along with the first two we had added prior.
vue for in list display


Mongo Express Vue.js Node.js Tutorial Summary

That concludes this tutorial which explored the basics of working with the MEVN stack. Of course you likely have heard of the MEAN stack which makes use of Mongo, Express, Angular, and Node. This approach removes Angular from the Stack and inserts Vue.js in it’s place. Interestingly, this was one of the first tutorials where the client side does nothing more than simply interact with an API. Express, Mongo, and Node worked together to provide the API while Vue.js provided the client side application that sends and receives JSON data with that API. Excellent!

|