Build your first ExpressJs server from scratch.
Tags: node, javascript, express
Published: 2019-12-01 18:08:50

## Hi everyone ,



<span style="font-size:1.28rem;">

In this article , i will show you how to spin up an Expressjs server using NodeJS. This tutorial will be pretty basic , and ideal for a beginner.
</span>


## So Let's get started.


<span style="font-size:1.28rem;">

make a new directory and go to that directory

if you are using [VScode](https://code.visualstudio.com/) you can open a directory , from CMD using `code .`

![Alt Text](https://thepracticaldev.s3.amazonaws.com/i/k7pjbcz6uelquoqbcyvw.PNG)


then run `npm init` to initialize a project.
if you are lazy like me you can run
`npm init -y` to initialize a project with default settings.

![Alt Text](https://thepracticaldev.s3.amazonaws.com/i/b9d54rhw5s7m8umn3ueu.PNG)

this will create a `package.json` file with the information you provide.
this file is an essential component for a npm project, since we specify many details about the project such as dependencies,scripts,licence etc. by looking at a `package.json` file you can get a rough idea about what is it. Enough with the `package.json` file.let's move on.

____

Now we successfully created a project , next thing is to install the dependencies.we need few dependencies to start making our server

1. [express](https://expressjs.com/) - to spin up our expressjs server
2. [body-parser](https://www.npmjs.com/package/body-parser) - a `middleware` to parse the body of incomming requests
3. [morgan](https://www.npmjs.com/package/morgan) - a `middleware` utility tool that logs the server events (this is not essential but useful for debugging)

to install these dependencies run `npm i express body-parser morgan`


![Alt Text](https://thepracticaldev.s3.amazonaws.com/i/gqga2vpsdzrd0o6qvlfx.PNG)


and also i highly recommend you to install [nodemon](https://www.npmjs.com/package/nodemon) . `nodemon` is also a utility tool that allows you to restart your server after changing the code , so you don't need to manually restart.

to install `nodemon` run `npm i -g nodemon`

now all the dependencies are installed and ready to go.


Next, we are going to create our first and only file. all mighty `app.js`

![Alt Text](https://thepracticaldev.s3.amazonaws.com/i/j86azzk46qzdgmhskrnv.PNG)

in the app.js file first, we will import the dependencies we installed.

`const express = require('express')` <br>
`const bp = require("body-parser")`<br>

then we will decide a port number where your server listens.
it's better to choose a port number higher than 1024 because there are privileged ports and they might require special access.
so let's stay in a safe zone.

`const port = 5000`<br>

next, we need to make an express app we can work with to that

`const app = express()`<br>

app.use() is a function that we use to attach middlewares to an express application.here what we are doing is attaching the middlewares for
`body-parser`, and `morgan`.it allows us to use their functionalities.

`app.use(bp.urlencoded({ extended: false }))`

`app.use(bp.json())`

`app.use(require("morgan")("dev"))`

Ok then now we have configured or app lets wire up our first route.

I'll start with a simple hello world `get` route.


<pre style="font-size:1.28rem;color:#A53477;background-color:black;">
app.get("/", (req, res) => {
 res.send("hello world");
});
</pre>

after specifying a route, we have to tell where should your app listen to. we only declare the variable with port, now we have to specify that port for listening.


<pre style="font-size:1.28rem;color:#A53477;background-color:black;">
app.listen(port, () => {
  console.log("Express server listning on port " + port);
});
</pre>

and after this, what left is to run our server. I will use nodemon to run the server.

`nodemon app.js`

if you didn't install `nodemon`, you can still run your app by

`node app.js`

if you did everything correctly, you can see Express server listening on port 5000 messages in your console.

![Alt Text](https://thepracticaldev.s3.amazonaws.com/i/t1wc3vsazpk93ig3kcjl.PNG)



now visit `http://localhost:5000/` with your browser. you can see you hello world text in the browser.

`if you used a different port use that specific port` 

![Alt Text](https://thepracticaldev.s3.amazonaws.com/i/ddhd6r4ciw4kkiaupzb6.PNG)

we can also see `morgan` logging some useful information in the console.

![Alt Text](https://thepracticaldev.s3.amazonaws.com/i/0y24isw6diqe30zjh89m.PNG)


let's dig deeper into `app.get()` function, we used it but we don't know how it works.

we used `app.get()` make a new get request route. you can make `PUT POST DELETE` requests upon your requirement.

`POST` and `GET` are the most common types of Http requests.

so here we used `app.get()` because we wanted a get request.
if you want to go with post request use `app.post()`

`app.get()` function first parameter we have to pass is our preferred `path`. this `path` is the string that specifies which route should it hit in the server.

for example if you used `helloworld`

<pre style="font-size:1.28rem;color:#A53477;background-color:black;">
app.get("/helloworld", (req, res) => {
 res.send("hello world");
});
</pre>

</span>
we can access it using `http://localhost:5000/helloworld`

![Alt Text](https://thepracticaldev.s3.amazonaws.com/i/ch78w9h8wb8uu86dcb71.PNG)

we will get and error message. that's because we didn't specify that path.

![Alt Text](https://thepracticaldev.s3.amazonaws.com/i/1w2czo1h5pl0cvhnzoo7.PNG)



next is a callback function with two objects `req`, `res`.

`req` object has all the information about the request like

headers request body etc.

`res` object well handle how you respond to that request.
`res.send()` method will send a plain text to that request as a response.
we also have `res.json()` which we can use to send JSON data.

<pre style="font-size:1.28rem;color:#A53477;background-color:black;">
app.get("/", (req, res) => {
  var obj = {
    name: "rizky"
  };

  res.json(obj);
});
</pre>

you can see we got a JSON response.

![Alt Text](https://thepracticaldev.s3.amazonaws.com/i/pjo528id6gdrrbc9skmc.PNG)

____


final `app.js`


{% gist https://gist.github.com/RizkyRajitha/ce35bd4f99e550f1bd42f28a52b93853 %}



</span>

## Thank you for reading until the end. If you have any unclear part feel free to drop a comment and I'll try my best to help you out. and if you have suggestions please let me know in the comment section.

## Cheers 🥂 , Have a Nice Day.