270 words
1 minutes
[Express.js] 3 - Router in express.js
[Basic] Router
The Router functions may help developers to split up different routing point, which brings the following advantages.
- π Better API management
- π¦ Clear coding structure
- π Easy to testing
Folder Structure
Letβs assume you have a folder like this
.
βββ package.json
βββ tsconfig.json
βββ appleRouter.ts
βββ orangeRouter.ts
βββ server.ts
Router Usage
1. Create Router.ts
Letβs create a appleRouter.ts
and type the following stuff.
Inside appleRouter.ts
import express from "express";
import { Request, Response } from "express";
// highlight-start
export const appleRouter = express.Router();
// highlight-end
// http://localhost:8080/apple/hi
appleRouter.get('/hi', async (req: express.Request, res: express.Response) => {
try {
return res.status(200).json({ status: true, data: "Hi this is apple" })
}
catch(err:any){
return res.status(200).json({ status: false })
}
});
Also, create a orangeRouter.ts
and type the following stuff.
Inside orangeRouter.ts
import express from "express";
import { Request, Response } from "express";
// highlight-start
export const orangeRouter = express.Router();
// highlight-end
// http://localhost:8080/orange/yo
orangeRouter.get('/yo', async (req: express.Request, res: express.Response) => {
try {
return res.status(200).json({ status: true, data: "Yo this is orange" })
}
catch(err:any){
return res.status(200).json({ status: false })
}
});
2. Add app.use()
Back to server.ts
, import the folloing router
and use app.use
to import the api.
Inside server.ts
import express from "express";
import { Request, Response } from "express";
// highlight-start
import { appleRouter } from "appleRouter"
import { orangeRouter } from "orangeRouter"
// highlight-end
const app = express();
app.get("/api", function (req: Request, res: Response) {
res.end("Hello mom!");
});
// highlight-start
app.use("/apple", appleRouter);
app.use("/orange", orangeRouter);
// highlight-end
const PORT = 8080;
app.listen(PORT, () => {
console.log(`Listening at http://localhost:${PORT}/`);
});
3. Testing
After all, you may test with your web.
Test with http://localhost:8080/apple/hi
{
status: true,
data: "Hi this is apple"
}
Test with http://localhost:8080/orange/yo
{
status: true,
data: "Yo this is orange"
}