Middleware?

PussinSocksΒ·2022λ…„ 7μ›” 18일
0

CloneCoding

λͺ©λ‘ 보기
5/20

What is it?

  • software in the middle πŸ™„
  • Middle of what => Between Request and Response.
  • All middlewares are handlers, and all handlers are middlewares(?)
  • middleware = handler = controller
  • controller has one more argument else than req and res: next
  • next is a function which execute the next argument on the request.
const middleWare = (req, res, next) => {
  cosnole.log("I'm in the middle");
  next();
};
const handleMain = (req, res) => {
	return res.send("this is response and I'm at the end");	
};

app.get("/", middleWare, handleMain);
  1. Browser is request GET "/" page.
  2. ExpressJS will call middleWare function
  3. middleWare function will execute next();
  4. next() function will execute the argument next to the middleWare argument ( which is handleMain).

So middleware bascially a clear custom which manage request


Global middleware

app.use(middleWare);
app.get("/", handleMain);

The order of the use() is important. Always put the global middleware top of the other routes.
if you put it under other get requests, It's not gonna work.

Summary

  1. middleware is one function which uses next.
  2. middleware can be applied in the get() function before the final argument.
app.get("/", middleware, hadleMaine);
  1. middleware can be used independently, with use() function. (Must be on top of other requests)
app.use(middlewareName);
  1. middleware makes it possible to control many things. (like who can get the access and who doesn't)
profile
On a journey to be a front-end developer

0개의 λŒ“κΈ€