Express是基于Node.js平台,一个快速、开放、极简的Web开放框架
Express的作用和Node.js内置的http模块类似,是专门用来创建Web服务器的。
本质上就是一个npm上的第三方包,提供了快速创建Web服务器的便捷方法
Express的中文官网:https://www.expressjs.com.cn/
安装
创建基本的Web服务器
1 2 3 4 5 6 7 8 9
| const express = require('express');
const app = express();
app.listen(8080,()=>{ console.log('服务启动成功 请访问:http://localhost:8080'); })
|
监听GET和POST请求的方法
1 2
| app.get('请求URL',function(req,res){}) app.post('请求URL',function(req,res){})
|
响应数据给客户端的方法
1 2 3 4 5 6 7 8 9 10 11 12
| app.get('请求URL',(req,res)=>{ res.send({ name: 'zs', age: 20, gender: '男'}) })
app.post('请求URL',(req,res)=>{ res.send('请求成功') })
res.send() 参数可以是 a Buffer object,a String,an object,an Array. res.end() 参数只能是Buffer 对象或者是字符串
|
获取URL 中携带的查询参数
1 2 3 4 5 6
| app.get('/',(req,res)=>{ console.log(req.query) })
|
获取URL中的动态参数
1 2 3 4 5 6 7
|
app.get('/user/:id',(req,res)=>{ console.log(req.params) })
|
补充知识点
- /:id 是自定义的变量
- 参数可以有多个,例如:地址为…/user/123/456 匹配/:ids/:name 值为{ ids:’123’, name:’456’ }
托管静态资源(就是将目录中的图片、css、JS等静态文件对外开放访问)
1
| app.use(express.static('文件夹名'))
|
注意: 在访问的时候目录名不会出现在URL中
1 2 3 4 5 6 7 8 9 10
| const express = require('express'); const app = express();
app.use(express.static('public')).listen(8080,()=>{ console.log('启动成功 http://localhost:8080'); })
|
托管多个静态资源目录
1
| app.use(express.static('public1'),express.static('public2'))
|
挂载路径前缀
1 2 3 4
| app.use('/public',express.static('public'))
|
nodemon
使用nodemon启动的项目被修改之后会被 nodemon 监听到,从而实现自动重启项目的效果
1 2
| npm i nodemon -g nodemon app.js
|
Express路由
在Express中,路由指的是请求地址和服务器处理函数之间的映射关系—从上往下匹配
由 请求的类型、请求的URL地址、处理函数 这三部分组成
1
| app.METHOD(PATH,HANDLER)
|
最简单的用法就是把路由挂载到 app 上去
1 2 3 4 5 6 7 8
| app.get('/login',function(req,res){ res.send('登录成功') }) app.post('/add',function(req,res){ res.send('添加成功') })
|
模块化路由的步骤
- 创建路由模块对应的
.js
文件
- 调用
express.Router()
函数创建路由对象
- 向路由对象上挂载具体的路由
- 使用
module.exports
向外共享路由对象
- 使用
app.use()
函数注册路由模块1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19
|
const express = require('express')
const router = express.Router()
router.get('/list', (req, res) => { res.send('用户列表') })
router.post('/add', (req, res) => { res.send('添加用户') })
module.exports = router
|
注册路由模块
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
|
const express = require('express') const app = express()
const userRouter = require('./router')
app.use('/user',userRouter)
app.listen(8080, () => { console.log('服务启动成功 http://localhost:8080') })
|