Routing Requests in Node Server
Aditya Chukka
Posted on May 30, 2021
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
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();
- 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"]}`);
});
- 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}`);
});
- 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"]}`);
});
- 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
fromitems.ts
import express from "express";
import { router as item_router } from "./items";
- Create an express app if you haven't already
const app = express();
const port = 3000;
- Route requests on items on app to
item_router
app.use("/tdsvc/item", item_router);
- 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}`);
});
- 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"
},
..
- 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
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
- Method:
-
Send a
POST
request to write an item- Method:
POST
- URL:
http://localhost:3000/tdsvc/item/
- Request
Body
withjson
format
{ "text": "item 1" }
- You should see a response as shown below
- Method:
-
Send a
PUT
request to update an item- Method:
PUT
- URL:
http://localhost:3000/tdsvc/item/1
- Request
Body
withjson
format
{ "text": "updated item" }
- You should see a response as shown below
- Method:
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();
- 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"]}`);
});
- 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}`);
});
- 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"]}`);
});
- Stitching all the above parts together we get our
users.ts
module
Using user
Route in app
- Import
router
fromusers.ts
import { router as user_router } from "./users";
- Route requests on users on app to
user_router
app.use("/tdsvc/user", user_router);
- 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
- Method:
-
Send a
POST
request to write an user- Method:
POST
- URL:
http://localhost:3000/tdsvc/user/
- Request
Body
withjson
format
{ "text": "user 1" }
- You should see a response as shown below
- Method:
-
Send a
PUT
request to update an item- Method:
PUT
- URL:
http://localhost:3000/tdsvc/user/1
- Request
Body
withjson
format
{ "text": "updated user" }
- You should see a response as shown below
- Method:
Parsing Requests Payload
- Add express.json to parse JSON payloads in request body
app.use(express.json());
- Add express.urlencoded to parses requests with urlencoded payloads
app.use(express.urlencoded({ extended: true }));
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.
Posted on May 30, 2021
Join Our Newsletter. No Spam, Only the good stuff.
Sign up to receive the latest update from our blog.