node.js入门→放弃Day4——中间件 概念(Middleware)

Exprexx 中间件

1.中间件

node.js入门→放弃Day4——中间件 概念(Middleware)_第1张图片

http://expressjs.com/en/guide/using-middleware.html

中间件的本质就是一个请求处理方法,我们把用户从请求到相应的整个过程分发到多个中间件中去处理,这样做的目的是提高代码的灵活性,动态可扩展的。

  • 同一个请求所经过的中间件都是同一个请求对象和相应对象

1.1 应用程序级别中间件

万能匹配(不关心任何请求路径和请求方法):

app.user(function (req, res, next) {
    console.log(1);
    next();
})

只要是以 ‘/xxx/’ 开头的:

app.use("/a", function (req, res, next) {
    console.log('2');
    next();
})

1.2 路由级别中间件

get:

app.get("/", function (req, res) {
    res.send("hello");
})

get:

app.get("/", function (req, res) {
    res.send("hello");
})

post:

app.post("/", function (req, res) {
    res.send("hello");
})

put:

app.put("/", function (req, res) {
    res.send("hello");
})

delete:

app.delete("/", function (req, res) {
    res.send("hello");
})

1.3 错误处理中间件

app.use(function (err, req, res, next) {
    console.error(err.stack);
    res.status(500).send("server busy....");
})

1.4 第三方中间件

http://expressjs.com/en/resources/middleware.html

  • body-parser
  • compression
  • coolie-parser
  • morgan
  • response-time
  • serve-static
  • session(express-session)

你可能感兴趣的:(Vue与Node学习)