DEV Community

Aditya Chukka
Aditya Chukka

Posted on

Routing Requests in Node Server

Routing in Express

In this post, we will learn how to route requests using Router on Express Server.

Preface

Routing determines how an application responds to a request for particular endpoint.

For an introduction to routing, please see Express docs

When a server manages multiple objects it results in serving multiple endpoints. At this point, it would become harder to main the application logic at one place. Express helps us divide the application logic based on objects it serves into individual routes.

We will demonstrate a simple example of routing on a node server

You can skip to tutorial and refer to this commit for source code

Requirements

  • This post assumes users have the knowledge of basic express server. If you are not familiar with it please refer to demo example

  • We will be using postman to test our end points

postman

Basic Application

In this section we will create two routes user and item.
For each of these routes we will add GET, PUT and POST HTTP Requests.

Route for items

  • Create a file items.ts
  • Create router from Express
import express from "express";
export const router = express.Router();
Enter fullscreen mode Exit fullscreen mode
  • Add HTTP GET Request to read an item
// GET Method
router.get("/:id", (req, res) => {
  res.send(`You are requesting an item with id: ${req.params["id"]}`);
});
Enter fullscreen mode Exit fullscreen mode
  • Add HTTP POST Request to write an item
// POST Method
router.post("/", (req, res) => {
  res.send(`You are posting an item with params: ${req.params}`);
});
Enter fullscreen mode Exit fullscreen mode
  • Add HTTP PUT Request to update an item
// PUT Method
router.put("/:id", (req, res) => {
  res.send(`You are updating an item with id: ${req.params["id"]}`);
});
Enter fullscreen mode Exit fullscreen mode
  • Stitching all the above parts together we get our items.ts module

Using item Route in app

  • Create index.ts if you have not already
  • Import router from items.ts
import express from "express";
import { router as item_router } from "./items";
Enter fullscreen mode Exit fullscreen mode
  • Create an express app if you haven't already
const app = express();
const port = 3000;
Enter fullscreen mode Exit fullscreen mode
  • Route requests on items on app to item_router
app.use("/tdsvc/item", item_router);
Enter fullscreen mode Exit fullscreen mode
  • Listen to requests on the port (3000)
app.listen(port, (err?) => {
  if (err) {
    return console.error(err);
  }
  return console.log(`server is listening on port: ${port}`);
});
Enter fullscreen mode Exit fullscreen mode
  • Stitching all the parts together, we get our index.ts

Running the server

  • If you are using node to run your server, use the flag --es-module-specifier-resolution=node
  • This tells node to import modules without extensions .js or .mjs
  • Update your start script in package.json
  "scripts": {
    "start": "tsc && node --es-module-specifier-resolution=node dist/index.js",
    "test": "echo \"Error: no test specified\" && exit 1"
  },
..
Enter fullscreen mode Exit fullscreen mode
  • Run your server by using the command npm start
  • You should see a message similar to below on your terminal
$ npm start

> tdsvc@0.1.0 start D:\Workspace\blog-series\tdsvc
> tsc && node --es-module-specifier-resolution=node dist/index.js  

server is listening on port: 3000
Enter fullscreen mode Exit fullscreen mode

Testing the requests on item

  • Open postman app or browser plugin
  • Send a GET request to read an item

    • Method: GET
    • URL: http://localhost:3000/tdsvc/item/1
    • You should see a response as shown below GET_ITEM
  • Send a POST request to write an item

    • Method: POST
    • URL: http://localhost:3000/tdsvc/item/
    • Request Body with json format
      {
        "text": "item 1"
      }
    
    • You should see a response as shown below POST_ITEM
  • Send a PUT request to update an item

    • Method: PUT
    • URL: http://localhost:3000/tdsvc/item/1
    • Request Body with json format
       {
         "text": "updated item"
       }
    
    • You should see a response as shown below PUT_ITEM

Route for users

Repeat the steps we did for items

  • Create a file users.ts
  • Create router from Express
import express from "express";
export const router = express.Router();
Enter fullscreen mode Exit fullscreen mode
  • Add HTTP GET Request to read an item
// GET Method
router.get("/:id", (req, res) => {
  res.send(`You are requesting an user with id: ${req.params["id"]}`);
});
Enter fullscreen mode Exit fullscreen mode
  • Add HTTP POST Request to write an item
// POST Method
router.post("/", (req, res) => {
  res.send(`You are posting an user with params: ${req.params}`);
});
Enter fullscreen mode Exit fullscreen mode
  • Add *HTTP PUT Request * to update an item
// PUT Method
router.put("/:id", (req, res) => {
  console.log(req);
  res.send(`You are updating an user with id: ${req.params["id"]}`);
});
Enter fullscreen mode Exit fullscreen mode
  • Stitching all the above parts together we get our users.ts module

Using user Route in app

  • Import router from users.ts
import { router as user_router } from "./users";
Enter fullscreen mode Exit fullscreen mode
  • Route requests on users on app to user_router
app.use("/tdsvc/user", user_router);
Enter fullscreen mode Exit fullscreen mode
  • Stitching both routes parts together, we get our new index.ts

Testing the requests on users

  • Run the server
  • Send a GET request to read an user

    • Method: GET
    • URL: http://localhost:3000/tdsvc/user/1
    • You should see a response as shown below GET_USER
  • Send a POST request to write an user

    • Method: POST
    • URL: http://localhost:3000/tdsvc/user/
    • Request Body with json format
      {
        "text": "user 1"
      }
    
    • You should see a response as shown below POST_USER
  • Send a PUT request to update an item

    • Method: PUT
    • URL: http://localhost:3000/tdsvc/user/1
    • Request Body with json format
       {
         "text": "updated user"
       }
    
    • You should see a response as shown below PUT_USER

Parsing Requests Payload

app.use(express.json());
Enter fullscreen mode Exit fullscreen mode
app.use(express.urlencoded({ extended: true }));
Enter fullscreen mode Exit fullscreen mode

Please check the full code in this commit

❤️ Congratulations 👏, you have successfully routed requests on a node server using Express and TypeScript

Thanks for reading through the entire article. Please reach out with questions, comments and/or feedback.

Top comments (0)