express
1. express 搭建服务
const express = require('express')
const app = express()
app.listen(7890)
2. express 路由
- 必须 method 和 path 全部匹配才执行对应的 callback
app[method](path, function(){})
app.all(*, function(){})
3. 路径参数路由
- 将匹配到的结果生成一个对象 放到
req.params上
app.get('/user/:id/:name')
req 上的属性
req.params // 路径擦书
req.url // 整个路径
req.path // pathname 路径
req.headers // 请求头
req.method // 请求方法
req.query // 获取请求参数 问号后边的参数
4. middleware 中间件
- 中间的作用
- 处理公共逻辑, 扩展 req, res
- 可以决定是否继续执行
- 开头匹配到就会执行中间件
- 错误中间件,在页面最后,参数是 4 个, 第一个参数是错误
err
res 新增方法
- res.json() // 返回一个 对象
- res.sendFile() // 绝对路径
- res.sendStatus()
- res.send()
练习
用户管理模块
- 登录 /login
- 注册 /reg
文章管理模块
- 发表文章 /post
- 删除文件 /delete
中间件 body-parser 的使用
// 使用
const bodyParser = require('body-parser')
// 解析表单格式 把表单内的数据 解析后放在 req.body 上
app.use(bodyParser.urlencoded({ectended: true}))
// 解析 json 格式 把字符串转化成对象 解析后放在 req.body 上
app.use(bodyParser.json())
路由拆分
const express = require('express')
const app = express()
const router = express.Router()
router.get('/', function(){
console.log('首页')
})
app.use('/user', router)
静态服务中间件
app.use(express.static('dirrectorName'))
来源:CSDN
作者:lijie627239856
链接:https://blog.csdn.net/lijie627239856/article/details/103598629