Basic Routing in NodeJS

πŸ› οΈ Introduction to Routing in NodeJS

When building web applications, routing is a fundamental concept. Routing in NodeJS (specifically using the Express framework) allows us to define how our server responds to different HTTP requests.

This guide will help beginners understand the basics of routing, how to test it using Postman, and how to send and receive data using different HTTP methods.

πŸ”§ Setting Up Postman for Testing Routes

To start testing your APIs, we recommend using Postman – a free and powerful API testing tool.

  • Why use Postman?

    • It helps you send HTTP requests (GET, POST, etc.)

    • You can view server responses easily

    • It supports sending headers, JSON, and even authentication tokens

πŸ“₯ Download Postman: https://www.postman.com/downloads

πŸ›£οΈ What is a Route in NodeJS?

In simple terms:

A route is a path on your server that responds to a client request.

For example:

sh
app.get(‘/login’, (req, res) => {
res.send(‘Login Page’);
});

When someone visits http://localhost:5000/login, the server responds with β€œLogin Page”.

This concept is central to Routing in NodeJS and helps you build structured, scalable APIs.

✍️ Basic Example Using index.ts (TypeScript)

Create a file named index.ts in your Node.js + TypeScript project, and paste the following code. This is a simple demonstration of how Routing in NodeJS works.

sh
// index.ts
// 1. Import express
import * as express from ‘express’;
// 2. Create an instance of express
const app: express.Application = express();
// 3. Start the server on port 5000
app.listen(5000, () => {
console.log(‘Server is running at port 5000’);
});
// 4. Define a basic GET route
app.get(‘/login’, (req, res) => {
const data = { first_name: ‘Sameer’, last_name: ‘Sundi’ };
res.send(data); // Send JSON response
});

βœ… What this does:

  • Starts a server at http://localhost:5000

  • When you visit /login, it responds with:

sh
{
“first_name”: “Sameer”,
“last_name”: “Sundi”
}

🚦 Common HTTP Methods in Routing

There are five commonly used methods when defining routes in Express:

sh
app.get() // Retrieve data
app.post() // Send new data
app.put() // Replace existing data
app.patch() // Update part of existing data
app.delete() // Remove data

✍️ Example Routes:

sh
app.get(‘/login’, (req, res) => { … });
app.post(‘/signup’, (req, res) => { … });
app.patch(‘/update/password’, (req, res) => { … });
app.delete(‘/delete/user’, (req, res) => { … });

These routes define what happens when a client accesses the specified path using a specific method.

πŸ“¬ Understanding req and res

  • req stands for request – the data coming from the client.

  • res stands for response – what your server sends back.

πŸ§ͺ Basic GET Route Example

sh
app.get(‘/login’, (req, res) => {
res.send(‘Success!’);
});

When tested in Postman (GET http://localhost:5000/login), the response will be:

  • Body: Success!

  • Status: 200 OK

🚨 Customizing HTTP Status Codes

You can change the status code manually to reflect the result of the request:

sh
app.get(‘/login’, (req, res) => {
res.status(404).send(‘Not Found’);
});

This returns a 404 Not Found message, which is helpful when a page or resource doesn’t exist.

πŸ“€ Sending JSON Data in Routing

Option 1: res.send() with JSON

sh
app.get(‘/login’, (req, res) => {
const user = {
first_name: ‘Sameer’,
last_name: ‘Sundi’
};
res.send(user);
});

Option 2: res.json()
sh
app.get(‘/login’, (req, res) => {
res.json({
first_name: ‘Sameer’,
last_name: ‘Sundi’
});
});

res.json() is cleaner and automatically sets the proper content-type header (application/json).

🧭 Creating Multiple Routes

You can create as many routes as needed for your application. Here are a few examples used in Routing in NodeJS:

sh
app.get(‘/profile’, (req, res) => {
res.send(‘User Profile’);
});
app.post(‘/signup’, (req, res) => {
res.send(‘Signup Successful’);
});
app.delete(‘/delete-account’, (req, res) => {
res.send(‘Account Deleted’);
});

Each route serves a specific function, making the API organized and predictable.

🧠 Summary of Routing in NodeJS

Term Description
Route A defined path handled by the server
req The request coming from the client
res The server’s response
GET Used to retrieve data
POST Used to send new data
PUT Replaces existing data
PATCH Updates partial data
DELETE Deletes data

 

Scroll to Top