express中的路由是为了处理不同的请求的,用来匹配请求地址,进行不同的处理
使用
基于,rest 风格的api接口(同一个接口命名,根据不同的请求类型,进行不同的处理)
定义路由
const express = require('express');const router = express.Router();const StudentServices = require('../../services/studentService')const { getResult } = require('./sendHelper')router.get('/', (req, res, next) => {StudentServices.findAndCountAll().then(resp => res.send(getResult(resp))).catch(err => next(err));})router.get('/:id', (req, res) => {res.send('查询单个学生')})router.post('/', (req, res, next) => {StudentServices.addStudent(req.body).then(resp => res.send(resp)).catch(err => next(err));})router.delete('/:id', (req, res) => {res.send('删除学生')})router.put('/:id', (req, res) => {res.send('修改学生')})module.exports = router;
其中getResult是为了同一格式返回数据,代码如下
exports.getResult = function (res) {return {code: 200,success: true,content: {total: res.total,data: res.data,}};};
使用路由
const express = require('express');const app = express();//创建一个以express应用,app实际上是一个函数,用于处理请求的函数const path = require('path');const rootPath = path.resolve(__dirname, '../public')/**** 发送请求的时,会根据请求的路径,从指定的目录中查找是否存在该文件,如果存在,则相应文件内容,而不再移交给后续的中间件,* 如果不存在文件,则直接移交给后续的中间件*/app.use(express.static(rootPath, {index: 'index.html' //默认访问页面,默认值为index.html,可修改}));// app.use('/static', express.static(rootPath))// 也可以针对访问某个指定api路径,来标识需要 返回静态资源/**** 默认res无法解析post请求的参数,也就是请求体* 使用该中间件后表示,当Content-Type是"application/x-www-form-urlencoded",使用该中间件处理*/app.use(express.urlencoded({extended: true}))/**** 默认res无法解析post请求的参数,也就是请求体* 使用该中间件后表示,当Content-Type是"application/json",使用该中间件处理*/app.use(express.json())// 除了api请求app.use('/api/student', require('./api/student'))app.use(require('./errMiddleware')) // 处理所有的错误请求app.listen(12306, () => {console.log('server on 12306 has started')})
app.use('/api/student',require('./api/student'))此处使用路由- 每次请求
/api/student,路由会根据不同的请求类型,做不同的处理
