Express Basics

image-20200331092006288

What is Express.js?

: Express is a minimal and flexible Node.js web application framework that provides a robust set of features to develop web and mobile applications.

Core Features

  1. Allows to set up middlewares to respond to HTTP Requests

  2. Defines a routing table which is used to perform different actions based on HTTP Method and URL

  3. Allows to dynamically render HTML Pages based on passing arguments to templates

Installation

1. Installing Express Locally

Install express

  • saves the installation locally in the node_modules

  • create a directory express inside node_modules

Express version check

Install modules along with express

2. Installing Express in the Project

Directory structure

1. create package.json

2. Install dependency by using npm

3. Create Express server

server.js

result

  • When opening the web server on port 8000, the text Cannot GET/ is displayed

    • why?

      • Because the Router hasn't been set up yet!

4. Basic Routing

server.js

5. Router

image-20200403223235009

It is good coding practice to write router code and server code in separate files!

  • Create a router folder

  • Create main.js

router > main.js

  • module.exports allows the router code to be imported and used as a module in server.js since it was written separately~!

5. Render HTML page

  • Create a views directory

  • Create html files

views > index.html

views > about.html

Modify server.js

Handling Static Files

Static Files

  • .js, css, image files used in HTML

  • To handle Static files on the Server, use the express.static() method!

  1. Create a public directory

  2. Create a css directory

  3. Create .css files

public > css > style.css

Modify server.js

Add CSS link to html files

result

127.0.0.1:8000/

image-20200404155824643

127.0.0.1:8000/about

image-20200404155934497

Last updated