Express

Express 框架核心特性:

1 可以设置中间件来响应HTTP请求

2 定义了路由表用于执行不同的HTTP请求动作

3 可以通过模板传递参数来动态渲染HTML页面

安装experss ,需要同时安装一下几个重要的模块:

body-parser - node的中间件,用于处理JSON rAW,tEXT和URL编码的数据

cookie-parser 这就是一个解析Cookie的工具。通过req.cookies 可以取到传过来的cookie,并把它们转成对象

multer - node中间件,用于处理enctype='multipart/form-data' (设置表单的MIME编码)的表单数据。

 静态文件

Express 提供了内置的中间件express.static来设置静态文件。

如果把静态文件放在public文件夹下,可以这样写:

app.use('/public',express.static('public'));

app.use('static',express.static('public')); 现在可以通过访问带有/static前缀地址来访问public目录中的文件了;

但是这样,express.static方法提供的是一个相对路径,如果运行express 的app在别的文件下,最好使用使用绝对路径:

app.use('/static',express.static(path.join(__dirname,'public')))

一个express应用可以使用一下类型的中间件:

1 应用层级的中间件

2 路由层级的中间件

3 错误处理中间件

4 内置的中间件

5 第三方的中间件

1 应用层及的中间件,

每次app接收一个请求都会执行

app.use(function(req,res,next){

console.log('Time:',Date.now());

});

特定的请求才会执行

app.use('/user/:id',function(req,res,next){

console.log('request type',req.method);

next();

});

路由器级中间件

app.get('/user/:id', function (req, res, next) {
  res.send('USER')
})

一个中间件可以有多个回调函数,这时前一个回调函数必须有第三个参数next,并执行next()方法把req res移交给下一个回调函数,否则下一个永远不会执行,如果没有执行next,并且也没有回应,这个请求会一直处于挂载状态

app.get('/user/:id', function (req, res, next) {
  // if the user ID is 0, skip to the next route
  if (req.params.id === '0') next('route')
  // otherwise pass the control to the next middleware function in this stack
  else next()
}, function (req, res, next) {
  // send a regular response
  res.send('regular')
})

// handler for the /user/:id path, which sends a special response
app.get('/user/:id', function (req, res, next) {
  res.send('special')
})

第二个中间件永远不会执行,做如下修改,第二个中间件会被执行

app.get('/user/:id', function (req, res, next) {
  // if the user ID is 0, skip to the next route
  if (req.params.id === '0') next('route')
  // otherwise pass the control to the next middleware function in this stack
  else next()
}, function (req, res, next) {
  // send a regular response
 console.log('regular')
next()
})

// handler for the /user/:id path, which sends a special response
app.get('/user/:id', function (req, res, next) {
  res.send('special')
})
2 路由层级的中间件和应用层级的中间件是一样的,除了路由层级中间件是绑定到express.router()的一个实例


































原文地址:https://www.cnblogs.com/xiaofenguo/p/12084336.html