Node + Express Basics Part I: Building a basic HTTP server
Tags: node, javascript, express, beginners
Published: 2022-10-25 03:42:22

This article is Part I of a three part series in which we will use node + express to learn how to build a RESTful API and test it with Postman.

In Part I we will have a look at how to set up a basic HTTP server with Node and Express

## Introduction

We can define a [HTTP server](https://developer.mozilla.org/en-US/docs/Learn/Common_questions/What_is_a_web_server) as software that understands URLs (web addresses) and HTTP (the protocol your browser uses to view web pages). 

A HTTP server can be accessed through the domain names of the websites it stores, and it delivers the content of these hosted websites to the end user's device.

Node is a JavaScript runtime environment that helps us run JavaScript outside the browser. Express is a Node.js framework that makes it easier for us to develop APIs with node, which by itself isn't as friendly for development

You can find the code for this on [my Github](https://github.com/DanielStai/http_server). Make sure you follow me there too :)

## 1. Setting up the project

Before we begin, you will need to install Node.js on your system and set up a local development environment. 

To do this, you can follow along [this tutorial](https://www.digitalocean.com/community/tutorial_series/how-to-install-node-js-and-create-a-local-development-environment) which describes how to install Node.js for different operating systems.

Once you've installed node (and `npm` by extension), create a directory for the project and `cd` into it. I'll call my directory `node_example`

```
mkdir node_example && cd node_example
```
Once in our projects directory, we will first run

```
npm init
```
to create a package.json file. 

We can now go ahead to install the required dependencies. In the terminal, go ahead and run

```
npm install express cors
```
This will install Express for us and also install the middleware CORS. 

CORS stands for cross origin resource sharing. The CORS package we are installing provides an Express middleware that enables CORS with different options so we can make the right connections on the network.

While we are at it, lets also install nodemon as a dev dependency. 

Why nodemon?

Every time you make changes to your files, we will need to restart the server for those changes to take effect. 

Nodemon takes care of that for us, saving us from the cumbersome task of always starting and restarting the server. Go ahead and run the following in the terminal

```
npm install -D nodemon
```
This will install nodemon as a dev dependency. 

Dev dependencies are packages that are installed to aid in the development process hence not needed in the production environment

Now we need to edit the package.json file so as to ensure `npm start` starts the server. We will do this by adding `"start":"node index.js"` to the `scripts` as shown below. Note that we will be creating our server in `index.js`.

``` json
"main": "index.js",
  "scripts": {
    "test": "echo \"Error: no test specified\" && exit 1",
    "dev": "nodemon index.js",
    "start":"node index.js"
  },
```
We have also created a script named `dev` that runs `nodemon index.js`

To use `import` statements in `index.js` instead of the usual 'require', we add a `type` of `module` to our package.json file.

```json
},
  "type":"module"
}
```


## 2. Writing our server code

We are now all set to start writing code to create our server

``` javascript
import express from 'express'
import  cors from 'cors'

const app = express()
const port = 4000
```
In the code block above, we will import express and cors using the import statement. 

We can import like this since we added `"type":"module"` to our package.json file.

We then create an express application by invoking `express()` and designate a port number in our `port` variable. 

We will hard code our port number now but in subsequent examples we will point the port variable to an environment variable in the `.env` file like so:

```
const port = process.env.VARIABLE_NAME || 4000
```
This will tell our application to assign the variable name `port` to an environment variable `VARIABLE_NAME` stored in our `.env` file and default to 4000 if no such environment variable exists in the `.env`

## 3.Configuring middleware

In the next code block, we will configure some middleware. 

``` javascript
app.use(cors())
app.use(express.json())
app.use(express.urlencoded({extended:true}))
```
We will not take a deep dive into middleware for now but we will define middleware as functions that execute some code that can have side effects on the app, and usually add information to the request or response objects.

The syntax used to load middleware is: 

```
app.use(<middleware_function>)
```
 
This mounts the middleware at root level. 

There are other ways to mount the middleware to specific routes or to a specific type of request but those are beyond the scope of this article.

## 4. Defining app routes

We will now define our app routes and specifically what gets sent with a get request to the root of our app ('/').

``` javascript
app.get('/', (request, response)=>{
    response.send('Hello World')
})

app.listen(port, ()=>{
    console.log(`Server is running on port ${port}`)
})
```

Express routes can be expressed (pun intended) as `app.METHOD(PATH, HANDLER)`. 

METHOD is our http method in lowercase, PATH is our relative path on the server and HANDLER is the function that express calls when the route is matched.

We then use `app.listen()` to define the port that our API server should be listening on

## 5. Running the server

And that's it. We have written all the code we need to create a basic http server. 

To run our server, type `npm run dev` in your terminal. If you followed all steps correctly, you should see `Server is running on port 4000` in your terminal.

On your browser, visit `http://localhost:4000` and you'll see 'Hello World' logged on the screen

In the next article we will define REST APIs and extend this example to a fully fledged REST API. You can [read the article here](https://dev.to/danielstai/node-express-basics-part-ii-building-a-restful-api-3fj9)