Creating a Simple Backend with Node.js and Express

This post will walk you through using Node and Express to set up a very basic backend. The purpose is to build an API capable of returning data in JSON format.

Initial Setup

To start we are going to need some things:

  • Node: This is the first thing you will need. Go to the site, download and install. Nothing special here.
  • Once Node is installed on your computer open up terminal and change directory (cd) to the location where you would like to build your app.
  • Time to begin. First create a directory for your app and cd into it. In your terminal:
$ mkdir exampleApp
$ cd exampleApp
  • Next, we will create a package.json file:
$ npm init

The terminal will prompt you for several things. Unless you want to specify, you can just hit ‘return’ for most of them. It’s worth noting the name of the file that is entered when you are prompted for an ‘entry point’ (it’s ok if you forget, you can always just check the package.json file). This file will be the main entry point for your program.

  • Now we need to install and include Express into our app. Express is a Node web application framework. To install run:
$ npm install express --save
  • We will be creating our server in index.js and will be making many changes. For these changes to take effect you will have to stop and restart the server. This gets to be SUPER annoying. To make this less painful we can install ‘nodemon’. This will watch for changes in our directory and automatically restart our node application when changes occur.
$ npm install -g nodemon

Create A Simple Route With Express

To start, lets just get the text “I EXIST” to show up in your browser.

  • To start, create a new file: index.js — then open it (in your text editor.)
  • We need to require/import express into our app. In index.js add:
const express = require('express')
const app = express()
  • Now lets use that app. The first route to make is one to our root or homepage:
app.get('/', function (req, res) {
res.send('I EXIST')
})

The .get() method takes a path (‘/’) as a string and a callback function (I used ES6 syntax, arrow function ) that accepts request and response arguments. In this simple example, any request is responded to with “I EXIST”.

  • Almost done — we still need a server. Add this below your route:
app.listen(3000, () => {
console.log('Server started on port 3000...')
})

The .listen() method takes a port number (3000) as an integer and a callback function. In this case, when the server is running, it will log the message “Server start on port 3000…” to the terminal.

Test The Simple App

At this point you should have two files (package.json and index.js) and some code in your index.js file. It should look something like this:

// Require Express
const express = require('express')
// Init App
const app = express()
// Home Route
app.get('/', (req, res) => {
res.send('I EXIST')
})
// Start Server
app.listen(3000, () => {
console.log('Server started on port 3000...')
})

Now lets start it up. Make sure in terminal you are in the root directory of the app (exampleApp/) and run:

$ nodemon

If everything is working you should see the message “Server started on port 3000…” in your terminal. Now, in your browser go to: http://localhost:3000/

You should see something like this:

Browser Showing “I EXIST”

Great! But this is kinda boring and pointless. Lets make this work like an API and render some JSON.

Rendering JSON — Simple API

As this post grows, I will include how to hook this app up to a database. For now, we are going to create a variable with some data and render it to the correct URL.

  • First, lets make some data. I’m putting this right above where my Home route is in the code. Here is the dummy-data I’m using (I’m pretending I have a list of articles that have a Title, Author, and Body Content):
const articles = [
{
id: 1,
title: "First Article",
author: 'Generic Error',
body: "These are words that I have written to show you some body content."
},
{
id: 2,
title: "Second Article",
author: 'Generic Error',
body: "BOOOOOOOOOOOO!"
},
{
id: 3,
title: "Third Article",
author: 'Generic Error',
body: "Oh hey there. Didn't expect you to still be here..."
}
]
  • Next, we need a route for API. Below the Home Route, add this route:
app.get('/api/v1/articles', (req, res) => {
res.json(articles)
})

This looks very similar to our home route. First, we set the path for our route: ‘/api/v1/articles’. The main difference to be aware of is what we send back as a response. Instead of using res.send() we will now use res.json(). This returns JSON as a response. Second, we pass the variable ‘articles’ to res.json() as an argument.

It should look something like this:

JSON Rendered In Browser

Using Node and Express to build a very basic server and render some data is very easy and requires very little code.

This will be updated to include how to hook this up to a database so it can be a real API.