ExpressJS: Beginners Guide
Tags: beginners, javascript, node, tutorial
Published: 2021-12-09 02:59:28

## 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](https://developer.mozilla.org/en-US/docs/Web/JavaScript), [Node](https://nodejs.org/en/), [frameworks](https://developer.mozilla.org/en-US/docs/Learn/Tools_and_testing/Client-side_JavaScript_frameworks), [npm](https://docs.npmjs.com/), [IDE](https://developer.mozilla.org/en-US/docs/Glossary/IDE), [dependencies](https://developer.mozilla.org/en-US/docs/Learn/Tools_and_testing/Understanding_client-side_tools/Package_management), 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](#pre)
  * [ExpressJS Intro](#intro)
  * [Setting Up Environment](#setup)
  * [Project Setup](#project)
  * [Express Server Setup](#server)
  * [Express Route Setup](#route)
  * [Express Listen Setup](#listen)
  * [Express Live Server](#live)
  * [Conclusion](#conclusion)


## Prerequisite <a name="pre"/>

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](https://code.visualstudio.com/) 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](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/0uyqtlw4tpgrjkqpd49d.png)
 


  

## ExpressJS Intro <a name="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](https://docs.npmjs.com/getting-started), 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}/`);
});
```

**_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}`)
})
```


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 <a name="setup" />

![Node Installation Page](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/nefcrx3agxv1j3vu1nq5.png)

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](https://nodejs.org/en/download/) 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](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/m23jhri9jrejgrwvd21f.png)

If you want to work on this guide right off your web browser is a starting code [code link](https://codesandbox.io/s/elegant-noyce-st6h7?file=/src/index.js) 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](https://www.npmjs.com/) 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
```

#### 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 <a name="project" />

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](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/gjbcyf1pigc6111h8k4p.png)

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
```

> if you have not yet installed [npm](https://docs.npmjs.com/getting-started) 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
```

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
```

![package.json file](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/myvvjho9m1u26qrlwno1.png)

> line 12 `dependencies` object holds our `express `package

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 <a name="server" />

![sever.js](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/9qcr3ksp7u9f6y9ft4qt.png)
 

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');
```

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();
```

Now that we have our `express` application all setup, we can now begin to setup out [routing](http://expressjs.com/en/guide/routing.html) 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 <a name="route" />

Here is a `get request` to our home page. 

```
server.get('/', (req, res) => {
  res.send('hello world');
})
``` 

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('/')
```

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](https://expressjs.com/en/4x/api.html)

```
server.get('/', function (req, res){})
```

Our file should look something like this now. 

![Server Listen](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/c9jqm11j3f4hyv8nu1kc.png)
 
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 <a name="listen" />

```
server.listen(3000)
```

Now our file should look like this. 

![Server Running](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/uno8cxyn1mp5nhzav33s.png)
 
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](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/e2l1bzqjoxmn5s99vjup.png)
 
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 <a name="live" />

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
```

![terminal example](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/q1cyeaiaruo8y5p5gqwe.png)
 

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

![local host site](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/0ybs0ns1dhahpi8ybb4i.png)

### Conclusion <a name="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!