Learn Express.js by doing
Published: 2021-08-26 02:18:35

Hello Devs, we're going to build a clothing store using Express.js!

You'll be learning:
* Express
* Middlewares
* Template Engines
* MVC
* MongoDB
* And a lot more!


Part 1 - Introduction

Part 2 - Creating a basic server express

First, we initiate our node project by using npm init 

Tip: You can use the flag -y to save the bla bla from the beggining

[image of the npm init]

Then, we need to install a couple of dependencies, the first one being express of course:

```sh
npm install express --save
```

We use the --save flag to save this dependency in our project.

And also, because the devmode, install nodemon and set up a "dev" script in your package.json

npm i nodemon --dev

We use the --also=dev flag because we only want this dependency in development mode

[setting the script]

Now, in your index.js file, let's create a basic express server, do not worry, I'm going to explain everything from the code.

First, we import our express package and save it into a constant.

See: When to use constant, let and var.

```js
const express = require("express");
```

Then, we instantiate the express object by calling the express function.
```js
const app = express();
```
Now, we set the port and hostname, we're going to know more about the process object in deployment, even though, if you want to learn more about process, see: What is the process object in node.js.

```js
const port = process.env.PORT || 3000;
const host = process.env.HOST || "127.0.0.1";
```
Now the actual express code, here we call the get method, first parameter is the path that we want to set up, and the second is a callback, also called the RequestListener in node.js, where we can play with the request and response objects.

For educational purposes, we're going to just send a basic response

```js
app.get("/",(req, res)=>{
    res.send("Index Page");
});
```
Now, we created a server, but we need to put it to listen to requests, we do that with the .listen method, that have various functions overloads (you can read about functions overloads here), but we're going to pass the port, the host name, and a callback that fires up when the server is initiated.

```js
app.listen(port,host,()=>{
    console.log("Server is running");
});
```

Now, if you do "npm run dev", you will see this on console:

[image of response]

And if you browse http://127.0.0.1:3000, you will see something like this:


[image]

Part 3 - Routes

Now, for our app, we defined the pages and structure in the introduction


[routes image]

First of all, is create the routes folder in the root folder of our project, At the same level of index.js file

<name_of_your_project>/routes

Inside of the routes folder, we create every Route Handler for our express application, let's create a shop.js file, that will be our ShopRouteHandler.

First, we import express again and this time, instantiate the Router object using the Router.function from the express package.
```js
const express = require("express");
const router = express.Router();
```

Now, with the router, we will be creating all of the shop routes, so you need to know beforehand, that our routes will have the "/shop" prefix

```js
router.get("/",(req, res)=>{
    res.send("All the categories here")
})
```
This will be sent when the /shop route is requested

Now, we're going to create the other routes

```js
router.get("/:category",(req, res)=>{
    let category_uri = req.params.category;
    res.send(category_uri);
});
```
This :category thing you see on the path, is actually a variable, we use the colon (not the literal human colon, but the double points) to identify parameters in our routes, so in this case, when the "/shop/shoes" endpoint is requested, the category_uri value will be shoes, and if the "/shop/jackets" endpoint is requested, the category_uri variable value will be 'jackets'

We do this because we need this data to search all the products related to this specific category in our Database

Now, following the same logic, let's create the same for subcategories and products, can you do it without seeing the code below? Take that challenge!

The answer:

```js
router.get("/:category/:sub_category",(req,res)=>{
    let category_uri = req.params.category;
    let subcategory_uri = req.params.sub_category;
    res.send(`You are seeing the ${subcategory_uri} of the ${category_uri} category`); 
});

router.get("/:category/:sub_category/:item",(req,res)=>{
    let category_uri = req.params.category;
    let subcategory_uri = req.params.sub_category;
    let item = req.params.item;
    res.send(`You are seeing the ${item} item of the ${subcategory_uri} subcategory of the ${category_uri} category`); 
});
```
Now, we need to export our router in order to use it outside this file, in the same file, we write:

```js
module.exports = router
```

You can read more about modules in javascript and node.js here, and you can read about import vs require here, and also, you can read module.exports vs export here.

Now, return to the index.js file, and require your shop.js file

```js
const shopRouteHandler = require("./routes/shop");
```

And set up the route handler using the app.use function, this will need to be on the top before any method calls, it needs to be at top after the requires

```js
app.use('/shop',shopRouteHandler);
```

Now, serve the app and you will visit the routes in order to confirm everything is done right.


4. Setting up view engines

For this course, we will use pug, but you can use EJS or Handlebars if you like! (and if you come from ruby on rails, these are something like erb in ruby!)

Now, we will install pug (Formerly known as jade), remember to save this dependency

Tip: Not knowing when to save a dependency? Learn here when to save a dependency in your project

```sh
npm i pug --save
```

Now, we need to config our app view engine, we can do that using the app.set() function, place this line of code before middlewares

```js
app.set('view engine','pug');
```

Now, we need to set the folder where our static assets will be, by default, we will be using the 'public' folder, so create it into the root of the project

```js
app.use(express.static('public'));
```

Also, create the views folder

[create the views folder]

Now, create an index.pug file inside the views folder and put this code on it

```pug
doctype html
html(lang="en")
    head
        meta(charset="UTF-8")
        meta(http-equiv="X-UA-Compatible", content="IE=edge")
        meta(name="viewport", content="width=device-width, initial-scale=1.0")
        title Document
    body 
        h1 index folder 
        p This is some content

```

Don't you know nothing about pug? Do not worry, look at this article on Crash Course on Pug

Now, we send the view as response in the "/" endpoint

```js
app.get("/",(req,res)=>{
    res.render('index')
});
```

The .render function searches the index.pug file inside the views folder of the project, we can also pass it arguments to use inside the pug file.