Node.js之Express详解

242 阅读4分钟

Express

Express 是基于 Node.js 平台,快速、开放、极简的 Web 开发框架

使用 Express,我们可以方便、快速的创建 Web 网站的服务器或 API 接口的服务器。

express的基本使用

安装

npm install express

npm i express@最新版本号

创建基本的web服务器

1.导入express模块

2.创建web服务器

3.调用app.listen()函数启动服务器

//1.导入express模块
const express = require('express');
//2.创建web服务器
const app = express();
//3.调用app.listen()函数启动服务器
app.listen(80, () => {
    console.log('running at http://127.0.0.1');
})

监听GET和POST请求

app.get('请求url', (req, res) => {
});
app.post('请求url', (req, res) => { 
});

获取url中携带的参数

通过req.query对象可以访问到客户端查询字符串的形式发送到服务器的参数

默认时一个空对象

app.get('/user', (req, res) => { 
console.log(req.query); 
res.send(req.query); 
});

获取url中的动态参数

通过req.params对象可以访问url中通过匹配到的动态参数

app.get('/:ids/:username', (req, res) => { 
console.log(req.params);
res.send(req.params) 
});

req.body

在服务器,可以使用 req.body 这个属性,来接收客户端发送过来的请求体数据

默认情况下,如果不配置解析表单数据的中间件,则 req.body 默认等于 undefined

// 导入 express 模块
const express = require('express')
// 创建 express 的服务器实例
const app = express()

// 注意:除了错误级别的中间件,其他的中间件,必须在路由之前进行配置
// 通过 express.json() 这个中间件,解析表单中的 JSON 格式的数据
app.use(express.json())
// 通过 express.urlencoded() 这个中间件,来解析 表单中的 url-encoded 格式的数据
app.use(express.urlencoded({ extended: false }))

app.post('/user', (req, res) => {
  // 在服务器,可以使用 req.body 这个属性,来接收客户端发送过来的请求体数据
  // 默认情况下,如果不配置解析表单数据的中间件,则 req.body 默认等于 undefined
  console.log(req.body)
  res.send('ok')
})

app.post('/book', (req, res) => {
  // 在服务器端,可以通过 req,body 来获取 JSON 格式的表单数据和 url-encoded 格式的数据
  console.log(req.body)
  res.send('ok')
})

// 调用 app.listen 方法,指定端口号并启动web服务器
app.listen(80, function () {
  console.log('Express server running at http://127.0.0.1')
})

路由

1.在 Express 中,路由指的是客户端的请求与服务器处理函数之间的映射关系

2.Express 中的路由分 3 部分组成,分别是请求的类型、请求的 URL 地址、处理函数

模块化路由

1.创建路由对应的js文件 //router.js test.js

2.调用express.Router()函数创建路由对象

3.向路由对象上挂载具体的路由

4.使用module.exports向外共享路由对象

5.使用app.use()函数注册路由模块

router.js //1.创建路由对应的js文件 router.js
const express = require('express');
//2.调用express.Router()函数创建路由对象
const router = express.Router();
//3.向路由对象上挂载具体的路由
router.get('/user/get', (req, res) => {
    res.send('GET success');
})
router.post('/user/post', (req, res) => {
    res.send('POST success');

});
//4.使用module.exports向外共享路由对象
module.exports = router;
test.js  //1.创建路由对应的js文件  test.js
const express = require('express');
const app = express();

//5.引入路由模块并使用app.use()函数注册路由模块
const router = require('./router');
app.use('/api', router);

app.listen(80, () => {
    console.log('server running at http://127.0.0.1');
    })

中间件

​ Express 的中间件,本质上就是一个 function 处理函数

function (req,res,next){
next();
}

全局生效的中间件

客户端发起的任何请求,到达服务器后都会先触发中间件

通过app.use(中间件函数)定义一个全局生效的中间件

//单个全局生效的中间件
const nw=(req,res,next)=>{
    next();
}
app.use(nw);

//简化形式
app.use((req,res,next)=>{
    next();
});

//多个全局生效的中间件
app.use((req,res,next)=>{
    console.log('第一个中间件')
    next();
});
app.use((req,res,next)=>{
     console.log('第二个中间件')
    next();
});

//会按照定义中间件的顺序来执行

中间件的作用

多个中间件之间,共享同一份 req 和 res,基于这样的特性,我们可以在上游 的中间件中,统一为 req 或 res 对象添加自定义的属性和方法,供下游的中间件或路由进行使用。

const express = require('express')
const app = express()

// 这是定义全局中间件的简化形式
app.use((req, res, next) => {
    // 获取到请求到达服务器的时间
    // const time = Date.now()
    var time = new Date();
    // 为 req 对象,挂载自定义属性,从而把时间共享给后面的所有路由
    req.startTime = time
    next()
})

app.get('/', (req, res) => {
    res.send('Home page.' + req.startTime)
})
app.get('/user', (req, res) => {
    res.send('User page.' + req.startTime)
})

app.listen(80, () => {
    console.log('http://127.0.0.1')
})

局部生效的中间件

不适应app.use()定义的中间件

//单个局部中间件
const nw=(req,res,next)=>{
    next();
}

app.get('/',nw,(req,res)=>{
    
})

//多个局部中间件
const nw=(req,res,next)=>{
    next();
}
const nw1=(req,res,next)=>{
    next();
}

app.get('/',[nw,nw1],(req,res)=>{
    
})

使用中间件的注意事项

1.一定要在路由之前注册中间件

2.客户端发送过来的请求,可以连续调用多个中间件进行处理

3.执行完中间件的业务代码之后,不要忘记调用 next() 函数

4.为了防止代码逻辑混乱,调用 next() 函数后不要再写额外的代码

5.连续调用多个中间件时,多个中间件之间,共享 req 和 res 对象