Express.js: Basic Introduction

ยท

5 min read

Express.js is a standard framework for Node.js that make using APIs fast and easy. Due to it's simplicity, it is used to write Express app instead of writing Node.js from scratch.

๐Ÿ’ก
Note that the order of calling/using functions, variables, etc. matters as it determines the order of their execution in Express.JS.

Express App

Let's write some codes...

To get started with Express, install it with following command:

npm install express

After that, create you express app by importing it in our node app:

const express = require("express");
// Invoke 'express()' to create app object
const app = express();
// Runs the callback if 'GET' method request done in '/' route
app.get("/", (req, res) => {
    res.send("Home Page");        // Send Response
});
app.listen(5000, () => console.log("Listening in Port 5000!!!"));
  • Here, 'express()' method returns an 'app' object that can be used somewhat like 'server' object returned by 'createServer()' from http module.

  • 'app.get()' looks for GET request done by client on specified route and runs the call-back function provided to it.

  • 'res.send()' sends response similar to 'res.write()' in http module.

  • 'app.listen()' listens to specified port number similar to 'server.listen()'. The callback given to it runs when server just starts to listen to the port.

  • The 'app' object not only listens to GET method but it can be used for:

App FunctionRequest Method
app.get()GET Method
app.post()POST Method
app.put() / app.patch()PUT / PATCH Method
app.delete()DELETE Method
app.all()GET, POST, PUT, DELETE

Express 404 Page

Creating page for invalid route can be done with '*' route:

const express = require("express");
const app = express();

app.get("/", (req, res) => {
    res.status(200).send("Home Page");    // Send Response with Status
});
// 404 Page
app.all("*", (req, res) => {
    res.status(404).send("Page Not Found");
});
app.listen(5000, () => console.log("Listening in Port 5000!!!"));
  • At first we handle request for required routes with required methods(GET, POST, PUT, DELETE).

  • Notice that we can chain 'res.status()' with 'send()' method to send response by manually specifying the status code.

  • For an invalid page, user can perform any of the request method, so we use 'app.all()' on '*' route (which means all routes) and handle it as 'Page Not Found'.

Now, you might be thinking if '*' denotes all routes then 'app.all()' should also put 'Page Not Found' on all the pages including Home Page. Shouldn't it?

๐Ÿ’ก
Remember when I said, order matters in Express.js?

All the pages handled before 'app.all()' by other methods will not be handled by 'app.all()'. Only the pages left unhandled are handled as 'Page Not Found'.

Static Assets

In my previous blog about http module, I mentioned an issue where we had to manually handle individual route in Node.js for each assets(Image File, CSS File, JavaScript File) that are referenced in our HTML file through URLs.

Those types of assets are generally static assets that server doesn't have to change. I can't imagine handling route for each and every assets manually when it comes to a larger project. This problem can be solved by Express.JS. Now, lets setup an example:

  • Create a HTML file named 'index.html' and refer static assets like images, CSS and JavaScript file.
<html>
    <head>
        <title>Navbar</title>
        <link rel="stylesheet" href="./styles.css" />
    </head>
    <body>
        <nav>
            <img src="./logo.svg" class="logo" alt="logo" />
            <ul class="links">
                <li><a href="#">home</a></li>
                <li><a href="#">about</a></li>
                <li><a href="#">contact</a></li>
            </ul>
        </nav>
        <script src="./script.js"></script>
    </body>
</html>
  • Now, put all the static assets inside a folder named 'public'. Your 'app.js' file should be as follows:
const express = require("express");
const path = require("path");
const app = express();

// 'static()' tells app to use static assets from 'public' folder
app.use(express.static("./public"));

app.get("/", (req, res) => {
    // 'sendFile()' used to provide HTML file as response
    res.status(200).sendFile(path.resolve(__dirname, "./index.html"));
});
// 404 Page
app.all("*", (req, res) => {
    res.status(404).send("Page Not Found");
});
app.listen(5000, () => console.log("Listening in Port 5000!!!"));
  • Here, 'app.use()' takes middleware as its argument and Express provides a middleware named 'static()' that tells the app to use the static assets from 'public' folder when needed.

  • Instead of 'send()', we are using 'sendFile()' to send HTML file as response. The 'path' module is utilized here to retrieve the HTML file from its location.

  • Now, whenever our app detect a URL to external assets(Eg: "./styles.css") in HTML file, it searches for that asset in 'public' folder and uses it.

In this way, we save our time by avoiding the need to manually specify each and every assets in our application.

But wait! We are not finished yet. I have a bonus point for you.

๐Ÿ’ก
Our app can now search 'public' folder for static assets and as you might know that the HTML file we sent as response is also a static asset. What happens if we put that HTML file in the 'public' folder?
const express = require("express");
const app = express();
app.use(express.static("./public"));

// No need to handle '/' route
//app.get("/", (req, res) => {});

app.all("*", (req, res) => {
    res.status(404).send("<h1>Page Not Found</h1>");
});
app.listen(5000, () => console.log("Listening in Port 5000!!!"));
  • Here, we are not handling the '/' route but it still works because our app will again search for static assets in 'public' folder and use the 'index.html' as the entry point which is equivalent to manually handling '/' route.

  • Again, the assets used by that 'index.html' is searched in the same 'public' folder as per requirement.

Congratulations, you made it till the end!

ย