# Creating Routes and Handling Requests with Express

* * *

## Introduction

Imagine you are building a website.

A user visits `/products` , clicks "Buy Now", submits a form and expects a response instantly.  
Now here is the problem,

**How does your server know what to do for each request?**

*   When someone visits `/` --> show homepage
    
*   When someone sends data --> process it
    
*   When someone hits unknown route --> return error
    

If you try doing this with raw Node.js, things get messy quickly.

That is where Express comes in --> it gives structure to chaos.

* * *

## Fundamentals

### What Express.js is

**Express.js** is a minimal web framework for Node.js that helps you,

*   Create servers easily
    
*   Define routes cleanly
    
*   Handle request and responses without boilerplate
    

Think of it like,

Node.js gives you raw tools  
**Express gives you a clean workspace to use those tools efficiently.**

* * *

## Why Express simplifies Node.js development

Let's quickly compare,

**Raw Node.js HTTP server**

```javascript
import http from 'http';

const server = http.createServer((req, res) => {
  if (req.url === '/' && req.method === 'GET') {
    res.end('Home Page');
  } else if (req.url === '/about' && req.method === 'GET') {
    res.end('About Page');
  } else {
    res.end('Not Found');
  }
});

server.listen(3000);
```

**Express version**

```javascript
import express from 'express';

const app = express();

app.get('/', (req, res) => {
  res.send('Home Page');
});

app.get('/about', (req, res) => {
  res.send('About Page');
});

app.listen(3000);
```

Difference,

*   No manual `if-else`
    
*   Cleaner routing
    
*   Readable and scalable
    

* * *

## Deep Dive

### Creating your first Express server

```javascript
import express from 'express';

const app = express(); // create app

const PORT = 3000;

// basic route
app.get('/', (req, res) => {
  res.send('Server is running');
});

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

**What’s happening?**

*   `express()` → creates app instance
    
*   `app.get()` → defines a route
    
*   `req` → incoming request
    
*   `res` → outgoing response
    
*   `app.listen()` → starts server
    

* * *

## Understanding Routing

Routing means --> When this URL + method is hit --> run this function

**Basic structure**

```javascript
app.METHOD(PATH, HANDLER);
```

Example:

```javascript
app.get('/users', (req, res) => {
  res.send('Users list');
});
```

**Visual flow**

![](https://cdn.hashnode.com/uploads/covers/6950f9416d11f7df08dde0d9/7c940d97-32d5-41b1-aade-55602658fa40.png align="center")

**Flow**

1.  Client sends request
    
2.  Express checks matching route
    
3.  Route handler runs
    
4.  Response is sent back
    

* * *

## Handling GET Requests

Used to fetch data

```javascript
app.get('/products', (req, res) => {
  const products = ['Phone', 'Laptop', 'Tablet'];
  res.json(products); // send JSON response
});
```

### Key points:

*   GET does not change data
    
*   Used for reading/fetching
    

* * *

## Handling POST Requests

Used to send data to server

First, enable JSON parsing,

```javascript
app.use(express.json());
```

Now handle POST

```javascript
app.post('/users', (req, res) => {
  const user = req.body; // data from client

  console.log(user);

  res.send('User received');
});
```

Example request body:

```javascript
{
  "name": "Mith",
  "age": 30
}
```

* * *

### Sending Responses

Express gives multiple ways to respond

```javascript
res.send('Text response');
res.json({ message: 'JSON response' });
res.status(404).send('Not Found');
```

### Common response types:

*   `res.send()` --> general purpose
    
*   `res.json()` --> API responses
    
*   `res.status()` --> set status code
    

* * *

### Express Routing Structure

![](https://cdn.hashnode.com/uploads/covers/6950f9416d11f7df08dde0d9/64af83d3-0df1-4cee-a08f-260adfe63c8c.png align="center")

As your app grows, routes should be separated,

```javascript
// routes/userRoutes.js
import express from 'express';

const router = express.Router();

router.get('/', (req, res) => {
  res.send('All users');
});

export default router;
```

```javascript
// app.js
import express from 'express';
import userRoutes from './routes/userRoutes.js';

const app = express();

app.use('/users', userRoutes);
```

* * *

## Practical Examples

**Example 1: Simple API**

```javascript
import express from 'express';

const app = express();

app.use(express.json());

// GET
app.get('/books', (req, res) => {
  res.json(['Book A', 'Book B']);
});

// POST
app.post('/books', (req, res) => {
  const newBook = req.body;
  res.json({
    message: 'Book added',
    data: newBook
  });
});

app.listen(3000);
```

**Example 2: Route with Parameters**

```javascript
app.get('/users/:id', (req, res) => {
  const userId = req.params.id;

  res.send(`User ID is ${userId}`);
});
```

`/users/10` → Output: `User ID is 10`

* * *

### Conclusion

At its core, Express is doing one simple job,

Take a request --> match a route --> run logic --> send a response

But the way it does it — cleanly and predictably — is what makes it powerful.

Once you understand routing, everything else in backend development starts making sense:

*   APIs
    
*   Authentication
    
*   Data flow
    

**If Node.js is the engine, Express is the steering wheel.**

* * *
