Getting Started With Node – Course

Creating Routers

Routers are simply an endpoint of a server. For example,, here the codeforgeek is a route.

We need to create routers in our web application to serve different requests.

We will create the following routes in our web application.

  • home
  • profile
  • login
  • logout

Express routers allow us to serve different HTTP methods such as GET, POST, PUT, DELETE, HEAD.

Here is how to create a router.

const express = require('express')
const app = express();
const router = express.Router();

router.get('/home', (req,res) => {
  res.send('<h2>Hello World, This is home router</h2>');

router.get('/profile', (req,res) => {
  res.send('<h2>Hello World, This is profile router</h2>');

router.get('/login', (req,res) => {
  res.send('<h2>Hello World, This is login router</h2>');

router.get('/logout', (req,res) => {
  res.send('<h2>Hello World, This is logout router</h2>');

app.use('/', router);

app.listen(process.env.port || 3000);
console.log('Web Server is listening at port '+ (process.env.port || 3000));

Let’s run our application, save the file and run the code using the following command.

node app.js

You should see the following message in the terminal.

express app start

Open your browser and visit the routes.

express home routes

Here is the profile page.

express profile page

You can also send HTML/JSON/XML as a response.

Related learning: Render HTML file in ExpressJS

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.