Setting up a node server with express.

Michael Carneal
2 min readJul 30, 2019

In my previous blog post I talked about how to set up a simple server with node.js.

In that example we used node to server custom routes that our front end was able to post and collect information from. The responses were parsed and we were able to read the body of that data and record it to our console.

One of the five basic rules of programming states that if someone else did the hard work why should you.

Enter Express.

Express is to java-script as Rails is to ruby. And it is wonderful.

If we go back to our first example we can alter the code but keep it very similar.

const http = require('http')   

const express = require('express')

We still need to import our HTTP library but we also need to add express to our project. We will do that by declaring a constant called ... express and import the express library to it.

now we can create our app variable and execute it with express.

const app = express()

Now lets add some routes and serve up some simple html.

app.use('/add-product', (req, res, next) => {
res.send('<form action="/product" method="POST"><input type="text" name="title"><button>add product</button></form>')
})

here we have a custom route to the /add-product page. This page will render and html input form and send its data to the /products route. Currently we don’t have /products route. So, lets make one.

app.post('/product', (req, res, next) => {
console.log(req.body)
res.redirect('/')
})

notice we used .post instead of use. The use method is an all inclusive method where as the .post method tells express this route will only be used for post responses.

But notice we are using console.logging req.body. Currently this should be registering as undefined to the node console. Lets fix that by doing the following.

npm the following packages to your projects

npm install --save body-parser

than add this to you app.js file

|const bodyParser = require('body-parser')

and magic!!!! we now have a way to parse the data we are requesting.

In our next entry we will create a show page, add a 404 page for failed routes, and consolidate our our routes in seperate folders for readability and long term scaling.

--

--