Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- import express, {Application, Request, Response, NextFunction} from "express";
- const app: Application = express();
- app.use(express.json());
- app.get('/', (req: Request, res: Response): Object => {
- return res.json({status: "success", message: "Welcome to API Service"});
- });
- // MIDLEWARE #1
- app.use((req: Request, res: Response, next: NextFunction) => {
- const error = new Error("Route not found.");
- });
- // MIDLEWARE #2
- app.use((error: {message: string; status: number}, req: Request, res: Response, next: NextFunction) => {
- res.status(error.status || 500);
- res.json({
- status: 'error',
- message: error.message
- });
- next();
- });
- const PORT: any = process.env.PORT || 3000;
- app.listen(PORT, () => console.log(`app listening on port ${PORT}`));
- 1) How middleware #1 know that the route not found? it suppose to run on every request?
- 2) Why does middleware #2 gets error as a parameter?
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement