express

Learning the Node JS Express framework

Express was one of the first major players on the Node.js framework scene and it continues to be one of the best Node.js frameworks today.

Let’s learn the Node js Express framework together by building a small example app!

1. Setting up a new Express project

Let’s open up our terminal and create a new folder. Then we’ll initialize npm and install express!

2. Node JS Express “Hello World”

Now that we have the project set up, let’s create a new file named server.js and put the following inside it:

This will load in the Express module, start a new server on port 3000 (you can change that to whatever you want!), create a new default “route” and return the words “Hello World!” when you go to it! We can test this by running:

From the terminal! Now go to http://localhost:3000 and you should see “Hello World!” on a blank white screen.

3. Adding Another Route

You can add as many routes as you’d like by adding more blocks like:

Now you can visit http://localhost:3000/foobar and see a different message!

4. Static Files

Eventually while learning the Node JS Express framework you’ll want to serve “static files”. These will likely be CSS and JavaScript files. Now, you could make an individual route for each file (style.css, script.js, etc) but that would get messy. So with Express.js you can do something like this:

Now you can put CSS, JavaScript and images in your “public” folder and access them from your app.

5. Sending Files

In our previous examples, we’ve been just sending down the text “Hello World!” to our users. Eventually we’ll need something more complex, like an HTML document. Let’s create a new file called index.html and put something like this inside.

This file still says “Hello World” but it will also request js/script.js and css/style.css — so let’s create those!

The last thing we need to do is change server.js so it’s sending the HTML file instead of the “Hello World!” text. Change it to look something like this:

If you want to have some more fun, put an alert in script.js and give the body a background color in style.css so you know it’s working!

Now you should have a basic Express.js application!

Jon Kuperman

Jon Kuperman is a Programmer, Teacher and Entrepreneur. He's currently blogging at Code Planet and podcasting at The Web Behind.

Leave a Reply

Your email address will not be published. Required fields are marked *