Routing Requests in Node Server
Tags: node, express, typescript, requestforpost
Published: 2021-05-30 03:29:09


![Routing in Express](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/lxpozxdy8pk3xhpea6kp.png)
 
In this post, we will learn how to route requests using [Router](https://expressjs.com/en/guide/routing.html) 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](https://expressjs.com/en/starter/basic-routing.html)

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](https://expressjs.com/en/guide/routing.html). 

We will demonstrate a simple example of routing on a [node server](https://github.com/achukka/tdsvc)

> You can skip to tutorial and refer to this [commit](https://github.com/achukka/tdsvc/commit/2490bc6745790abfd62a020923db1899c26485d4) 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](https://dev.to/achukka/create-server-using-express-and-typescript-2cf0)

- We will be using [postman](https://www.postman.com/) to test our end points

![postman](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/d0dw7159244re74tx4ba.jpg)
 

## Basic Application

In this section we will create two routes `user` and `item`. 
For each of these routes we will add [GET](https://developer.mozilla.org/en-US/docs/Web/HTTP/Methods/GET), [PUT](https://developer.mozilla.org/en-US/docs/Web/HTTP/Methods/PUT) and [POST](https://developer.mozilla.org/en-US/docs/Web/HTTP/Methods/POST) HTTP Requests.


### Route for items

- Create a file `items.ts`
- Create router from [Express](https://expressjs.com/en/4x/api.html#express.router)
```javascript
import express from "express";
export const router = express.Router();
```
- Add **HTTP `GET` Request** to read an item
```javascript
// GET Method
router.get("/:id", (req, res) => {
  res.send(`You are requesting an item with id: ${req.params["id"]}`);
});
```
- Add **HTTP `POST` Request** to write an item
```javascript
// POST Method
router.post("/", (req, res) => {
  res.send(`You are posting an item with params: ${req.params}`);
});
```
- Add **HTTP `PUT` Request** to update an item
```javascript
// PUT Method
router.put("/:id", (req, res) => {
  res.send(`You are updating an item with id: ${req.params["id"]}`);
});
```
- Stitching all the above parts together we get our `items.ts` module
{% gist https://gist.github.com/achukka/8676445ece0059d07b61a178d03dc44e file=items.ts %}

### Using `item` Route in app
- Create `index.ts` if you have not already
- Import `router` from `items.ts`
```javascript
import express from "express";
import { router as item_router } from "./items";
```
- Create an express app if you haven't already
```javascript
const app = express();
const port = 3000;
```
- Route requests on items on app to `item_router`
```javascript
app.use("/tdsvc/item", item_router);
```
- Listen to requests on the `port` (3000)
```javascript
app.listen(port, (err?) => {
  if (err) {
    return console.error(err);
  }
  return console.log(`server is listening on port: ${port}`);
});
```
- Stitching all the parts together, we get our `index.ts`
{% gist https://gist.github.com/achukka/8676445ece0059d07b61a178d03dc44e file=index_1.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`
```json
  "scripts": {
    "start": "tsc && node --es-module-specifier-resolution=node dist/index.js",
    "test": "echo \"Error: no test specified\" && exit 1"
  },
..
```
- Run your server by using the command `npm start`
- You should see a message similar to below on your terminal
```bash
$ 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
```

### Testing the requests on item

- Open [postman](https://www.postman.com/) 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](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/6djrtvk6exmov7wkd75i.png)

- Send a `POST` request to write an item
    - Method: `POST`
    - URL: `http://localhost:3000/tdsvc/item/`
    - Request `Body` with `json` format
      ```json
      {
        "text": "item 1"
      }
      ```
    - You should see a response as shown below
    ![POST_ITEM](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/rfpbph6uhqjgsj358u8r.png)

- Send a `PUT` request to update an item
    - Method: `PUT`
    - URL: `http://localhost:3000/tdsvc/item/1`
    - Request `Body` with `json` format
       ```json
       {
         "text": "updated item"
       }
       ```
    - You should see a response as shown below
    ![PUT_ITEM](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/i7o7ebmnipapwvyfma08.png)
 
### Route for users

> Repeat the steps we did for `items`

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

{% gist https://gist.github.com/achukka/8676445ece0059d07b61a178d03dc44e file=users.ts %}

### Using `user` Route in app
- Import `router` from `users.ts`
```javascript
import { router as user_router } from "./users";
```
- Route requests on users on app to `user_router `
```javascript
app.use("/tdsvc/user", user_router);
```
- Stitching both routes parts together, we get our new `index.ts`

{% gist https://gist.github.com/achukka/8676445ece0059d07b61a178d03dc44e file=index_2.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](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/914ht18u7e7osacddylc.png)

- Send a `POST` request to write an user
    - Method: `POST`
    - URL: `http://localhost:3000/tdsvc/user/`
    - Request `Body` with `json` format
      ```json
      {
        "text": "user 1"
      }
      ```
    - You should see a response as shown below
    ![POST_USER](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/oww9iqq8hfxebec98bb0.png)

- Send a `PUT` request to update an item
    - Method: `PUT`
    - URL: `http://localhost:3000/tdsvc/user/1`
    - Request `Body` with `json` format
       ```json
       {
         "text": "updated user"
       }
       ```
    - You should see a response as shown below
    ![PUT_USER](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/zxl2iqnwv2x75lin04qa.png)

## Parsing Requests Payload

- Add [express.json](http://expressjs.com/en/api.html#express.json) to parse JSON payloads in request body
```javascript
app.use(express.json());
```
- Add [express.urlencoded](http://expressjs.com/en/api.html#express.urlencoded) to parses requests with urlencoded payloads
```javascript
app.use(express.urlencoded({ extended: true }));
```

{% gist https://gist.github.com/achukka/8676445ece0059d07b61a178d03dc44e file=updated_index.ts %}


Please check the full code in this [commit](https://github.com/achukka/tdsvc/commit/2490bc6745790abfd62a020923db1899c26485d4)

❤️ 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.