DEV Community

Oscar Ortiz
Oscar Ortiz

Posted on • Updated on

 

ExpressJS: Beginners Guide

Introduction

A few things to note before getting started with this guide, we will be using a lot of terminology in this guide regarding to the topics like JavaScript, Node, frameworks, npm, IDE, dependencies, and a bit more. I recommend that you have some basic understanding on some of these topics before jumping straight into the guide.

Table of contents

Prerequisite

You will need a few things downloaded onto your machine in order to get started. First we need to choose where we will write our code, we will be using our own code editor Visual Studio Code for this project, this code editor provides many useful Developer tools to make our lives easier when coding our projects. You are more welcome to use what ever code editor you'd like, but for this project we will be using VS Code. Second we need to download our NodeJS environment to allow us to write up our server scripts which we importantly need. Third we need to make sure we have npm fully setup onto our machine as well. We will go over these topics on how to get them onto our systems and ready for future projects.

By the end of this guide you will have your expressjs server live on your local browser ready to use.
Finished

ExpressJS Intro

A lightweight yet powerful NodeJS Module. Yes at the end of the day ExpressJS is just another Module / Library that's part of NodeJS. So why use it if we have Node instead? Well it helps us handle a lot of the hard work and simplifies it to less code so that you have more time on other things. If you wanted to create a server with Node, you will have to write a bit more code just for a server to get up and running. With express they managed to handle a lot of the heavy lifting and helped us with simply writing less code than usual. Also the way we will be installing our packages is with node package manager or also known as npm. If you have not created an account with npm, then I suggest you do so since it is required for this guide. Please follow the setting up your account guide and come back after you're all set up!

NodeJS Server Setup

const http = require('http');

const hostname = '127.0.0.1';
const port = 3000;

const server = http.createServer((req, res) => {
  res.statusCode = 200;
  res.setHeader('Content-Type', 'text/plain');
  res.end('Hello World');
});

server.listen(port, hostname, () => {
  console.log(`App listening at http://${hostname}:${port}/`);
});
Enter fullscreen mode Exit fullscreen mode

ExpressJS Server Setup

const express = require('express')
const server= express()
const port = 3000

server.get('/', (req, res) => {
  res.send('Live Express Server')
})

server.listen(port, () => {
  console.log(`App listening at http://localhost:${port}`)
})
Enter fullscreen mode Exit fullscreen mode

In today's guide we will be setting up our very first ExpressJS Server. Don't worry if you don't know what is going line for line, we will go over each step through this guide to help you get a better understanding on how to use ExpressJS's API and work with it for future projects.

Setting Up Environment

Node Installation Page

In order to get started using ExpressJS we need to make sure we first have NodeJS installed. If you do not have NodeJS installed, it is recommended to install Node onto your machine if you want to follow along, here is a download link if you want to install Node onto your machine. We will be using our own Code Editor with for this guide to get some practice initializing and installing our packages.

CodeSandBox Start Code

If you want to work on this guide right off your web browser is a starting code code link for this guide. If you decide to use CodeSandBox make sure to fork it onto your account to be able to make changes and save it incase you want to return to it later on. Adding packages is a bit more different on CodeSandBox but we will cover how to do that too. You can skip to the Project setup section if you decide to take this route.

Version Check

Now that we have Node installed onto our local machine we can now start working with our node modules and even download node packages with the npm command lines. This is how we have access to a ton of other modules just like ExpressJS. After you have installed we can open up a command prompt to check if we have it on our machine.

node --v // command to check node version installed
Enter fullscreen mode Exit fullscreen mode

Windows

To see if Node is installed, open the Windows Command Prompt, Powershell or a similar command line tool, and type node -v . This should print the version number so you'll see something like this v0. 10.35 . Test NPM.

Mac

To see if Node is installed, type node -v in Terminal. This should print the version number so you'll see something like this v0. 10.31 .

Linux

To see if Node. js is installed, type node -v in the terminal. This should print the version number, so you'll see something like this: v0. 10.35 .

Project Setup

Now like any other project we need to have a location for all of our files. Lets create a folder where we will have our server stored in. You can name it anything you want. For this example I'll just use Intro since this is an intro to Express.

Empty Folder

On VS code open up your terminal and you should be at the root of your folder. To check your path on your terminal simply type in the following command onto the terminal. pwd and your output should be something like this. It might be a bit longer bit you get the idea.

If you are on codeSandBox then you should be able to added dependencies with their dependencies feature.

C:\user\dev\Intro
Enter fullscreen mode Exit fullscreen mode

if you have not yet installed npm onto your local machine please do so now as it is required for the following steps in this guide

Now that we are on the root level of our folder we can intialize our node_modules folder to allow us to add dependencies to our project or in other words npm packages.

Type in the following command onto your command line to create our package.json file. This will setup a new package.json file for us, where our dependencies will be stored for our project.

npm init --yes
Enter fullscreen mode Exit fullscreen mode

Now that we have some where to store our dependencies for our project we can now install express into our project. Notice how we also have a new folder node_module this is where all of our modules are stored. For now we wont worry to much about that.

npm install express
Enter fullscreen mode Exit fullscreen mode

package.json file

line 12 dependencies object holds our expresspackage

Now we have our Express module onto our project. Now we can begin to setup our server. Lets create our server.js file where we will have our express server generated in code.

Setting Up Express Server

sever.js

The first thing we need to do is include our express module onto our file. We will store our express module onto a variable where we will be able to use it freely through our app. We use the require method to access our module.

const express = require('express');
Enter fullscreen mode Exit fullscreen mode

Now that we have access to our module, we have to invoke now so we don't have to keep repeating our ourselves when we want to access the methods within our express module. We can store our invoked function inside a variable so we only call it once and can access it's methods freely.

const server = express();
Enter fullscreen mode Exit fullscreen mode

Now that we have our express application all setup, we can now begin to setup out routing for our app. We can access our routing methods right out of our server variable. This is where all of our http module would come in play but luckily we don't have to write out so much code with express.

Express Route Setup

Here is a get request to our home page.

server.get('/', (req, res) => {
  res.send('hello world');
})
Enter fullscreen mode Exit fullscreen mode

When using our get() method on our app, we are using express helper functions. Inside this function we pass in our path as the first argument in this example we are targeting the homepage. We pass in our path with a string, if you had an api database setup already this would be a link we can access and get data back to the user.

server.get('/')
Enter fullscreen mode Exit fullscreen mode

The second parameters is our route handler or callback function in other words. Route handlers can be in the form of a function, an array of functions or combination's of both. For this example we are only going to send back a response to the user's browser. We do this with our response object. Our response object has methods for us to use to get a response back to the user. Her we will simply send back a string message.

If you want to dive deeper on how things work check out the API refrence

server.get('/', function (req, res){})
Enter fullscreen mode Exit fullscreen mode

Our file should look something like this now.

Server Listen

Are Express app isnt ready just yet but almost. We now need to have our application listen for connections on the paths given.
We will use the listen method to help us assign a port.

Express Listen Setup

server.listen(3000)
Enter fullscreen mode Exit fullscreen mode

Now our file should look like this.

Server Running

We can send back a message to our console to let us know our server is running with a callback function within our listen method parameters.

Server Complete

Now this is where we will use our node environment to start our server. Make sure to save your files if you are using your own editor before you start your server.

Express Live Server

Type this node command in your terminal to get your server started. Your server will run at your localhost:port. Port will be what ever number you used.

node index.js
Enter fullscreen mode Exit fullscreen mode

terminal example

Now go onto your browser and type in your localhost:port url.

local host site

Conclusion

Congratulations!! You have now created your very own express server with just a few simple lines!! If this was pure node we would have written a lot more code. This is how developers are allowed to deliver faster by not having to worry to much about the basic structure and worry more about their application structure.

I hope by the end of this article you managed to learn how to create and understood what is going on in every line of code. It is very important to understand how your code fully works, not only does it help you become a better developer but can also help you use the tools you are working with more efficient.

These articles are mostly intended for personal use on becoming a better programmer, writer, and grow my programming skills. Feel free to drop any feedback or corrections that you believe that should be made to help me and others. Thank you for your time for sticking this far!

Top comments (0)

Visualizing Promises and Async/Await 🤯

async await

☝️ Check out this all-time classic DEV post