Learn Express.js

singhpritpal04

Pritpal Singh

Posted on January 26, 2024

Learn Express.js

Node.js is a runtime environment for running Javascript on servers(outside browsers).

Express.js is a Node.js web framework for building APIs and web applications using JavaScript.

1. Now see the following code:

const express = require('express');
const app = express();
Enter fullscreen mode Exit fullscreen mode
  • Here, we are using the require function to import the Express.js framework for using it in our application.
  • In the following line of code, we execute express(). This creates an instance of the Express application and stores it in the app variable. This variable can be used to define the routes, middleware, and other components of your web application.

2. Routing and HTTP Methods

Web frameworks provide resources such as HTML pages, scripts, images, etc. at different routes.

2.1. Define Routes

The following function is used to define routes in an Express application −
app.method(path, handler)

  • This METHOD can be applied to any one of the HTTP verbs – get, set, put, delete.
  • Path is the route at which the request will run.
  • Handler is a callback function that executes when a matching request type is found on the relevant route.

2.2. HTTP Methods

app.get('/',(req,res)=>{ 
  console.log("Hello World");
})
Enter fullscreen mode Exit fullscreen mode

-The get method is used to send a request to the server to retrieve data.

  • In addition, there are other fundamental methods such as POST, PUT and DELETE.

  • In this second line, we are printing Hello World.

3. Middleware

  • "A middleware is a function that sits between the request (req) and response (res) objects in an application's processing pipeline."

  • Middleware functions are functions that have access to the request object (req), the response object (res), and the next function in the application’s request-response cycle.

Image description

Image description

  • Middleware functions are executed in the order they are declared in the application. Each middleware function has access to the next function, which is used to pass control to the next middleware in the stack.
app.use((req, res, next) => {
  console.log('This middleware runs first');
  next();
});

const myMiddleware = (req, res, next) => {
  console.log('This is a custom middleware');
  next(); // Call the next middleware in the stack
};

app.use(myMiddleware);
Enter fullscreen mode Exit fullscreen mode

4. Dynamic Routing

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

app.get('/:username',(req,res)=>{ 
  res.send(`Welcome ${req.params.username}`);
})

app.listen(5000);
Enter fullscreen mode Exit fullscreen mode
  • We are displaying the request we sent as a query.
  • To receive a response from the server on the window, the send method is used.
  • The code app.listen(5000) indicates that it is being executed on port number 5000.

5. Template Engine

HTML is not equipped to perform calculations or JavaScript operations. In the backend, web developers do not use HTML directly. Instead, they use template engines such as Ejs, Pug, and others to create HTML templates. These template engines are often used to create dynamic web pages.

5.1. EJS

Embedded JavaScript templating is a simple templating language that lets you generate HTML markup with plain JavaScript.

  • Install EJS
npm i ejs
Enter fullscreen mode Exit fullscreen mode
  • Configure EJS
app.set("view engine",""ejs")
Enter fullscreen mode Exit fullscreen mode
  • To proceed, please create a folder named 'views' and then create ejs files inside it.

  • Instead of using the send method, we use the render method to automatically locate the ejs file (within the views folder).

  • To use JavaScript inside Embedded JavaScript (EJS), we can simply declare it within <%- -%> tags.

  • When passing values to ejs, always declare them as <%= value %>.

5.2. EJS use case

  • We will create a 'views' folder and create two ejs files inside it.

  • The first file is named header.ejs:

<!DOCTYPE html>
<html lang="en">

<head>
    <title>Document</title>
</head>

<body>
    <h1>Welcome <%=user.name %>
    </h1>
Enter fullscreen mode Exit fullscreen mode
  • The second file is named hello.ejs:
<%- include('header'); -%> //here we are rendering header file inside another ejs file which is possible.
    <h2>Email : <%=user.email %></h2>
    <h3>Age : <%=user.age %></h3>
    <ul>
        <% user.skills.forEach((items)=>{ %>
            <li><%=items %></li>
        <% }) %>
    </ul>
</body>
</html>
Enter fullscreen mode Exit fullscreen mode
  • In our JavaScript file, we will use the EJS file to display/render the content.
const express = require('express');
const app = express();

app.set('view engine','ejs');
app.get('/hello',(req,res)=>{
    const user = {
        name: 'abcde',
        email: 'abc@xyz.in',
        age: 20,
        skills: ['html','css','Js','React','Nodejs']
    }
    res.render('hello',{user});  
});

app.listen(5080);

Enter fullscreen mode Exit fullscreen mode

The render method sends a user object to the hello.ejs file and then renders it.

6. Static Files

  • Static files, such as images, JavaScript, and stylesheets, are used in web applications.

  • We will create a 'public' folder containing three subfolders named images, javascripts, and stylesheets.

  • Now, we will use this code in our file to make use of static files:

app.use(express.static('./public'))
Enter fullscreen mode Exit fullscreen mode
  • Now we no longer need to specify the full address of a static file to use it. For example, if we want to use a CSS file, we only need to provide the link as ./stylesheets/style.css instead of ./public/stylesheets/style.css.

7. Error Handling

Error Handling refers to how Express catches and processes errors that occur both synchronously and asynchronously.

Now declare this after the last route declared:

app.use(function errorHandler (err, req, res, next) {
  if (res.headersSent) {
    return next(err)
  }
  res.status(500)
  res.render('error', { error: err })
})
Enter fullscreen mode Exit fullscreen mode
  • We are storing the error message, referred to as err, in a variable called error. This variable is then sent to the route named ./error.
app.get('/error', (req, res, next) => {
  throw new Error('BROKEN')
})
Enter fullscreen mode Exit fullscreen mode
  • We are storing the word 'BROKEN' in the 'error' variable. -Whatever ejs view we set to the ./error route can display this text using <%= error %> tag.

8. Express Generator

Use the application generator tool, express-generator, to quickly create an application skeleton.
To install it:

 npm install -g express-generator
Enter fullscreen mode Exit fullscreen mode

After installation, we need to create an Express application:

express myapp --view=ejs
npm i
Enter fullscreen mode Exit fullscreen mode

After executing the command in the terminal, the entire structure that we previously had to create manually is now generated automatically, and two new folders named "routes" and "bin" are also created.
Instead of using app.get(), we will now use route.get() to handle our routing.

To run the application:

npm start
Enter fullscreen mode Exit fullscreen mode

or

npm nodemon
Enter fullscreen mode Exit fullscreen mode

nodemon is a package that eliminates the need to manually save and reload code, making programming more efficient.

9. Sessions and Cookies

Sessions are data that are stored on the server while Cookies are data that are stored on the client side.

9.1. Sessions

  • Sessions are more secure than cookies as it is saved on the server side.

  • To proceed with the task, we must first install 'express-session' and then add it to the 'app.js' file.

Then do the following coding:

app.use(expressSession({
resave: false,
saveUninitialized: false,
secret: "rndomxxxx"
}))
Enter fullscreen mode Exit fullscreen mode
  • The term "resave" refers to the action of not saving the session if there have been no changes in the values.

  • saveUninitialized means don't save the data which is not defined.

  • secret is the encryption string.

app.get("/",function (req,res){
req.session.ban= true;
res.render("index")
})

app.get("/removeban",function (req,res){
req.session.ban= false;
res.send("ban remmoved")
})
Enter fullscreen mode Exit fullscreen mode
  • We are setting the value of a variable to "true" but for route"/". The variable can be named anything.
app.get("/checkban",function (req,res){
console.log(req.session)
})
Enter fullscreen mode Exit fullscreen mode
  • To delete any session manually we will need to write req.session.destroy.

**Note: **The sessions are automatically deleted upon restarting.

9.2. Cookies

  • To proceed with the task, we must first install 'cookie-parse' and then add it to the 'app.js' file.

Then add this to the app.js:

app.use(cookieParser())
Enter fullscreen mode Exit fullscreen mode
  • Create a Cookie:
app.get("/",function (req,res){
res,cookie("age",25);
res.render("index")
})

Enter fullscreen mode Exit fullscreen mode

We are setting the value of a variable named age to "25" but for route"/". The variable can be named anything.

  • Reading Cookies:
app.get("/read",function (req,res){
console.log(req.cookies);
res.send("check")
})
Enter fullscreen mode Exit fullscreen mode

To get specific cookie, we will use req.cookies.age.

  • Delete a Cookie:
app.get("/clear",function (req,res){
res.clearCookie("age");
res.send("cleared")
})
Enter fullscreen mode Exit fullscreen mode

10. Connect-Flash

  • We will be using a package called connect-flash to flash messages.
  • This package enables data transfer between routes using sessions, without which it will not function.
const flash = require("connect-flash")

app.use(expressSession({
resave: false,
saveUninitialized: false,
secret: "rndomxxxx"
}))
app.use(flash())
Enter fullscreen mode Exit fullscreen mode

We can now utilize the flash.

app.get("/pass",function (req,res){
req.flash("age",17);
req.flash("name","ABC");
res.send("created")
})

app.get("/check",function (req,res){
console.log(req.flash("age"),req.flash("name"))
})
Enter fullscreen mode Exit fullscreen mode
💖 💪 🙅 🚩
singhpritpal04
Pritpal Singh

Posted on January 26, 2024

Join Our Newsletter. No Spam, Only the good stuff.

Sign up to receive the latest update from our blog.

Related

Learn Express.js
tutorial Learn Express.js

January 26, 2024