Advertisement
Guest User

Node JS Express Question.

a guest
Nov 15th, 2019
227
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. import express, {Application, Request, Response, NextFunction} from "express";
  2.  
  3. const app: Application = express();
  4.  
  5. app.use(express.json());
  6.  
  7. app.get('/', (req: Request, res: Response): Object => {
  8.     return res.json({status: "success", message: "Welcome to API Service"});
  9. });
  10.  
  11. // MIDLEWARE #1
  12. app.use((req: Request, res: Response, next: NextFunction) => {
  13.     const error = new Error("Route not found.");
  14. });
  15.  
  16. // MIDLEWARE #2
  17. app.use((error: {message: string; status: number}, req: Request, res: Response, next: NextFunction) => {
  18.     res.status(error.status || 500);
  19.     res.json({
  20.         status: 'error',
  21.         message: error.message
  22.     });
  23.     next();
  24. });
  25.  
  26. const PORT: any = process.env.PORT || 3000;
  27.  
  28. app.listen(PORT, () => console.log(`app listening on port ${PORT}`));
  29.  
  30. 1) How middleware #1 know that the route not found? it suppose to run on every request?
  31. 2) Why does middleware #2 gets error as a parameter?
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement