Express中间件(Middleware)
中间件的本质就是一个请求处理方法,我们把用户从请求到响应的整个过程分发到多个中间件去处理,这样做的目的是为了提高代码灵活性,动态可拓展。
- 中间件默认接收三个参数
function (req, res, next){}- req 请求对象
- res 响应对象
- next 调用下一个中间件的方法
- 当一个请求进来,会从第一个中间件开始匹配,如果匹配则会进入中间件,不匹配则会去找下一个中间件匹配
- 当一个请求进入一个中间件之后,如果不调用
next方法则会停留在当前中间件 - 如果调用
next方法时传递了参数,则会直接往最后面找到有四个参数的应用程序级别的中间件,通常是传入err错误对象,抛出错误给专门处理错误的中间件处理
app.get('/a', function (req, res, next) {fs.readFile('./adadada/', function (err, data) {if (err) {next(err)}})})....// 配置错误处理的中间件app.use(function (err, req, res, next) {res.status(500).send(err.message)})
- 如果没有一个能匹配的中间件,则返回
Cannot GET/POST ...中间件种类
💻参考:https://github.com/senchalabs/connect#middleware
前端发送ajax异步请求的过程发生了什么?
- 前端发送ajax请求
// 前端ajax异步请求(axios封装)async fetch() {await this.$http.post('http://localhost:3000/admin/api/categories', this.model)}
- 后端接收请求
- express.Router
- 使用express.Router类来创建可安装的模块化路由处理程序,Router实例
const route = express.Router()是完整的中间件和路由系统
- 使用express.Router类来创建可安装的模块化路由处理程序,Router实例
- app.use()
- express使用中间件(function),可选参数
path的默认路径为 “/“ ```javascript const express = require(‘express’) const app = express() const router = express.Router()
- express使用中间件(function),可选参数
- express.Router
router.post(‘categories’)
app.use(‘/admin/api’, router) // 服务端监听3000端口 app.listen(3000)
3. 服务端处理数据库- 连接数据库```javascript// 小技巧 导出一个函数,然后在入口文件(index.js)加括号传入app参数直接调用module.exports = app => {const mongoose = require('mongoose')// 指定连接的数据库不要求一定是已存在的,不存在会自动帮你创建好mongoose.connect('mongodb://127.0.0.1:27017/node-vue-moba', {useNewUrlParser: true})}// 在node执行的入口文件导入后执行require('../../db.js')(app)
创建数据模型
const mongoose = require('mongoose')const schema = new mongoose.Schema({name: {type: String}})// 导出 Categoty 模型module.exports = mongoose.model('Category', schema)
根据用户行为操作数据模型
// 小技巧 导出一个函数,然后在入口文件(index.js)加括号传入app参数直接调用module.exports = app => {const express = require('express')// express子路由const router = express.Router()// 导入Category数据模型const Category = require('../../models/Category')// 添加请求路由方法// 分类接口router.post('/categories', async (req, res) => {const model = await Category.create(req.body)res.send(model)console.log(req)})// 子路由挂载app.use('/admin/api', router)}


