Hello Express

Creating a basic web server with Express

Scroll down...

Content

Resources

Comments

Let's warm up our Express skills with the most straightforward of servers. We will first look at how to set up a new repo for our app, get Express installed, and finally create and serve up a jaw-dropping "Hello, World" page.

Set Up

First, let's make a new directory and use npm init to create our package.json file.

mkdir hello

// This creates our package.json file.
// The -y flag tell it to use the default options
npm init -y

Next, we will use npm to install Express.

npm install express --save

The --save flag will tell npm to save the package under dependencies (check out this link for a more detailed sxplanation of dependencies) in package.json. Your package.json file should now look something like this:

{
  "name": "hello",
  "version": "1.0.0",
  "description": "",
  "main": "index.js",
  "scripts": {
    "test": "echo \"Error: no test specified\" && exit 1"
  },
  "keywords": [],
  "author": "",
  "license": "ISC",
  "dependencies": {
    "express": "^4.14.1"
  }
}

Now that we have Express installed, let's build the actual—very basic—application.

Building the Express Application

Let's begin by creating the JavaScript file that will house all of the Express code for this very simple application.

touch index.js

Now, open this file in your favorite text editor. It does not take very much code at all to get a basic Express application wired up. The following code—ripped directly from the Express docs with only minor branding adjustments—is all you need.

const express = require('express')
const app = express()

app.get('/', function (request, response) {
  response.send('Hello Viking!')
})

app.listen(3000, function () {
  // This function is run when the app starts up.
  console.log('Kemst þó hægt fari.')
})

The express function is first required using the magic of Node, and then calling it creates an application object which we store as the app constant.

The app is chock-full of functions corresponding to HTTP methods. They each allow you to bind a route handler function to a particular URL pattern for the given HTTP method. In this case, when our app receives a get request to the top-level path (/), it will send back the string "Hello Viking!" as its response:

// It's nearly English! Sort of...
  app.get('/', function (request, response) {
    response.send('Hello Viking!')
  })

Simply run node index.js and open http:///localhost:3000 in your browser. Voila:

Hello, You!

Getting Dynamic

Let's alter our program such that it greets a name encoded in the URL. So if we visit "/names/Odin", we should see "Hello Odin!" displayed in the browser.

We will grab this information off of the URL by using Route Parameters. Express will pattern match the URL string, supplying any path components prefixed with a colon as parameters on the request object. Here's all the new code we need to add our new behavior:

  app.get('/names/:name', function (req, res) {
    const name = req.params.name
    res.send('Hello ' + name)
  })

As you can see, the :name Route Parameter was automatically added to the params object under the given key. We then simply interpolate this value into our response (here using ES6's string interpolation).

Wrapping Up

With Express, you can create a simple web server in less than 10 lines of code—of course, we could make this even shorter if we were willing to sacrifice readability. Although this application is incredibly simple, it does exhibit the properties shared by nearly every web application. Most importantly, it responds to a request with dynamically generated data.

The beauty of Express lies in its simplicity. It merely handles the boundaries of our system, the request, and the response. The rest is simply JavaScript. We can replace the body of either of our callback functions with as much complicated business logic as we desire. While there are a few more details to express, like Templates and Middleware (which we'll get to in the next lessons), you have more than enough to build a web application of extraordinary complexity. Let's keep going!



Sign up to track your progress for free

There are ( ) additional resources for this lesson. Check them out!

There are no additional resources for this lesson just yet!

Sorry, comments aren't active just yet!