Skip to main content

Command Palette

Search for a command to run...

Creating Routes and Handling Requests with Express .

Building Routes with Express.js

Updated
4 min read
Creating Routes and Handling Requests with Express .

What Express.js is .

So before understanding what Express.js is, let’s first look at the problem statement, why we actually needed Express.

  • In Node.js, the problem was that in backend development we had to write a lot of logic manually. There were very few built-in middleware, so most of the things had to be written from scratch.

  • In terms of routing, there was no proper separation of concerns. So if in the future the codebase grew with many routes, controllers, and other logic, it became very difficult to manage.

  • As the application scaled, understanding and maintaining the code also became difficult.

  • Another problem was that writing APIs was a bit difficult syntax wise. So to solve these problems, Express was introduced.

  • What Express does is provide a flexible and simple syntax along with many useful features. Because of this, writing routes became easier, and creating middleware also became simple.

  • This led to better separation of concerns, more standardized code, and improved maintainability. It also made building APIs much easier. So Express basically solved these problems, and that's what Express is.

If you read further, you will understand more about it.

Why Express simplifies Node.js development .

Because its main purpose is to make it easier to create servers and simplify things like routing, middleware, and request–response handling.

  • If you use Node.js directly, you often need to write a lot of boilerplate code to handle routes, manage requests, and send responses. But Express.js simplifies all of this and provides a cleaner and faster way to build backend applications.

  • With Express.js, you can easily define routes, handle different types of HTTP requests like GET and POST, use middleware for validation and authentication, and manage responses in a structured way.

  • It also provides a flexible structure, so you can organize your code properly and scale your application as it grows.

Creating first Express server .

Below is a express server code . Imported express first, then create function and inside this function, create express basic server started code, and use middleware and start server at port 3000

import express from "express";

async function createExpress() {
  const app = express();

  const PORT = process.env.PORT || 3000;

  app.use(express.json());

  app.get("/health", (req, res) => {
    res.json({ message: true });
  });
 

  app.listen(PORT, () => {
    console.log(`Server is running on port ${PORT}`);
  });
}

createExpress();

Handling GET requests .

So in a GET request, what happens is that the user wants to get something from the application. For example, if the user wants to get their own details, then they will use a GET request.

So to fetch that data, they need to create a GET request. Below is a simple example of a GET request in Application.

app.get('/user', async (req, res) => {
   console.log('Hello User');
   return res.status(200).json(req.body);
})

Handling POST requests .

  • In a POST request, what happens is that the user sends some data, and that data needs to be stored in the database. So obviously, to send (post) data, we use a POST request.

  • That's why we use POST requests. For example, when a new user comes to a website, they need to register for the first time. So first, they fill in their details, and then those details are sent and stored in the database. That's why we use a POST request.

Below is the code — you can check it.

app.post('/register', async (req, res) => {
    const data = req.body;
    
    console.log(`Check User Data`, data);

    return res.status(201).json({
              message: "User register Success",
              data: data
         });
}) 

Sending responses .

  • From sending a response, you can already understand that when a user sends a request, we must send a response back, whether it is an error response or a valid response.

  • It always needs to be sent. If you don't send a response, the request will get stuck there, and the user will not receive any acknowledgement.

  • So to send a response, you return it, then add a status code, and then the response message.

  • The code is given below you can check it.

  • In this below code i am just telling you how response sent .

    app.get('/user', async (req, res) => {
         try {
           console.log('Get User', req.body);
    
           const data = req.body;
            
           return res.status(200).json({
                  message: "User Get Success",
                  data: data
            })
        } catch (err) {
          return res.status(500).json({
            message: err
        })
      }
    })
    
💡
So with my above explanation i hope you understand what i learn and what's my thought process on Creating Routes and Handling Requests with Express