DEV Community

Pedro Uzcátegui
Pedro Uzcátegui

Posted on • Edited on

Learn Express.js by doing

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:

npm install express --save
Enter fullscreen mode Exit fullscreen mode

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.

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

Then, we instantiate the express object by calling the express function.

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

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.

const port = process.env.PORT || 3000;
const host = process.env.HOST || "127.0.0.1";
Enter fullscreen mode Exit fullscreen mode

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

app.get("/",(req, res)=>{
    res.send("Index Page");
});
Enter fullscreen mode Exit fullscreen mode

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.

app.listen(port,host,()=>{
    console.log("Server is running");
});
Enter fullscreen mode Exit fullscreen mode

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

/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.

const express = require("express");
const router = express.Router();
Enter fullscreen mode Exit fullscreen mode

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

router.get("/",(req, res)=>{
    res.send("All the categories here")
})
Enter fullscreen mode Exit fullscreen mode

This will be sent when the /shop route is requested

Now, we're going to create the other routes

router.get("/:category",(req, res)=>{
    let category_uri = req.params.category;
    res.send(category_uri);
});
Enter fullscreen mode Exit fullscreen mode

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:

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`); 
});
Enter fullscreen mode Exit fullscreen mode

Now, we need to export our router in order to use it outside this file, in the same file, we write:

module.exports = router
Enter fullscreen mode Exit fullscreen mode

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

const shopRouteHandler = require("./routes/shop");
Enter fullscreen mode Exit fullscreen mode

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

app.use('/shop',shopRouteHandler);
Enter fullscreen mode Exit fullscreen mode

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

  1. 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

npm i pug --save
Enter fullscreen mode Exit fullscreen mode

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

app.set('view engine','pug');
Enter fullscreen mode Exit fullscreen mode

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

app.use(express.static('public'));
Enter fullscreen mode Exit fullscreen mode

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

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

Enter fullscreen mode Exit fullscreen mode

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

app.get("/",(req,res)=>{
    res.render('index')
});
Enter fullscreen mode Exit fullscreen mode

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.

Top comments (0)