• vue+express+mysql+elementUI实现前后端交互增删改查


    简介:使用 Vue + koa + koa2-router + mySql + elementUI实现前后端交互

    页面整体效果图:
    前端页面 elementUI
    编辑页面:

    编辑页面

    添加页面:

    添加信息

    删除操作:

    在这里插入图片描述

    数据库客户端使用Navicat for mysql 当然你需要下载安装

    在数据库新建 stuInfo 表和表结构
    在这里插入图片描述
    stuInfo 表数据

    在这里插入图片描述

    在src目录下新建api/index.js中加入请求,响应拦截器和接口 api

    import axios from 'axios'
    const baseURL = './api'
    
    // 添加请求拦截器
    axios.interceptors.request.use(
      function(config) {
        // 在发送请求之前做些什么
        console.log('请求数据', config)
        config.url = baseURL + config.url
        return config
      },
      function(error) {
        // 对请求错误做些什么
        return Promise.reject(error)
      }
    )
    
    // 添加响应拦截器
    axios.interceptors.response.use(
      function(response) {
        // 对响应数据做点什么
        console.log('响应数据', response)
        return response
      },
      function(error) {
        // 对响应错误做点什么
        return Promise.reject(error)
      }
    )
    
    // 查询
    export const queryData = params => {
      return axios.get('/query', params)
    }
    // 添加
    export const addData = params => {
      return axios.post('/add', params)
    }
    // 修改
    export const updateData = params => {
      return axios.put('/updateData', params)
    }
    // 删除
    export const delData = params => {
      return axios.delete(`/delete/${params.id}`) // 注意这里的路径要和后端的路径一直,不然会报 404
    }
    
    // 查询teach表
    export const queryTeac = () => {
      return axios.get('/queryTeac')
    }
    
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27
    • 28
    • 29
    • 30
    • 31
    • 32
    • 33
    • 34
    • 35
    • 36
    • 37
    • 38
    • 39
    • 40
    • 41
    • 42
    • 43
    • 44
    • 45
    • 46
    • 47
    • 48
    • 49
    • 50
    • 51
    • 52

    nodejs 服务端核心代码:
    db.js 模块中配置数据库连接mysql

    // 引入 mysql 模块
    const mysql = require('mysql')
    
    // 配置数据
    const dbConfig = mysql.createPool({
      host: 'localhost',
      port: '3306', // 端口
      user: 'root',
      password: 'Fyl123456',
      database: 'test', // 数据库名称
      multipleStatements: true, // 多语句查询
    })
    
    function query(sql, value) {
      return new Promise((resolve, reject) => {
        dbConfig.query(sql, value, (err, result) => {
          if (err) {
            reject(err)
          } else {
            resolve(result)
          }
        })
      })
    }
    
    module.exports = query
    
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27

    配置接口路由文件:

    // 引入 koa 模块
    const koa = require('koa')
    
    // 实现接口的增删改查 get/post/put/delete
    const Router = require('koa-router') // 引入接口路由
    const db = require('./db.js') // 数据库配置
    const cors = require('koa2-cors') // 跨域依赖
    const bodyparser = require('koa-bodyparser') // 情趣提
    
    // 实例化 koa, router对象
    const app = new koa()
    const router = new Router()
    
    // 搭建服务
    // app.use(async (ctx) => {
    //   ctx.body = 'hello koa!'
    // })
    
    router.get('/index', async (ctx) => {
      ctx.status = 200
      ctx.body = 'hello koa'
    })
    
    // 查询
    router.get('/query', async (ctx) => {
      ctx.status = 200
      const info = ctx.request.body
      try {
        // const sql = `select * from stuInfo where(name=name or name="") limit ?,?`
        const sql = `select * from stuInfo where(name=name or name="")`
        const value = [info.name]
        const _data = await db(sql, value)
        ctx.body = {
          errorMessage: '',
          result: true, // true 成功, false 失败
          data: _data,
          pageSize: 10,
          pageNum: 1,
        }
      } catch (error) {
        ctx.body = {
          errorMessage: '',
          result: false,
          data: null,
        }
      }
    })
    
    // 添加
    router.post('/add', async (ctx) => {
      ctx.status = 200
      const info = ctx.request.body
      if (!info.id && !info.name) {
        ctx.body = {
          errorMessage: '数据添加失败学号和姓名是必填项',
          result: true, // true 成功, false 失败
          data: _data,
        }
        return
      }
      try {
        const sql =
          'insert into stuInfo(id, name, age, address, gender) values(?,?,?,?,?)'
        let param = [info.id, info.name, info.age, info.address, info.gender]
        await db(sql, param)
        ctx.body = {
          errorMessage: '',
          result: true,
          data: null, // 添加成功,后端不需要返回什么
        }
      } catch (error) {
        ctx.body = {
          errorMessage: '添加失败',
          result: false,
          data: null,
        }
      }
    })
    
    // 修改
    router.put('/updateData', async (ctx) => {
      ctx.status = 200
      const infos = ctx.request.body
      if (!infos.id) {
        ctx.body = {
          errorMessage: '学号是必填项',
          result: fasle,
          data: null,
        }
        return
      }
      try {
        const sql = 'update stuInfo set name=?,gender=?,age=?,address=? where id=?'
        let params = [infos.name, infos.gender, infos.age, infos.address, infos.id]
        await db(sql, params)
        ctx.body = {
          errorMessage: '',
          result: true,
          data: null,
        }
      } catch (error) {
        ctx.body = {
          errorMessage: '修改失败',
          result: false,
          data: null,
        }
      }
    })
    
    // 删除
    router.delete('/delete/:id', async (ctx) => {
      ctx.status = 200
      console.log(ctx)
      const param = ctx.params
      try {
        const sql = 'delete from stuInfo where id=?'
        let value = [param.id]
        await db(sql, value)
        ctx.body = {
          errorMessage: '',
          result: true,
          data: null,
        }
      } catch (error) {
        ctx.body = {
          errorMessage: '删除失败',
          result: false,
          data: null,
        }
      }
    })
    
    // 查询 teaInfo 表
    router.get('/queryTeac', async (ctx) => {
      ctx.status = 200
      try {
        const sql = 'select * from teacInfo'
        const _data = await db(sql)
        ctx.body = {
          errorMessage: '',
          result: true, // true 成功, false 失败
          data: _data,
        }
      } catch (error) {
        ctx.body = {
          errorMessage: '',
          result: false,
          data: null,
        }
      }
    })
    
    // 注册接口路由
    router.use('/api', router.routes())
    
    // 配置路由
    app
      .use(cors()) // 使用 nodejs cors 模块
      .use(bodyparser()) // 解析 body 请求体
      .use(router.routes()) // 接口路由
      .use(router.allowedMethods())
    
    // 监听端口
    app.listen(3000, () => {
      console.log('successfully listen at port 3000......')
    })
    
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27
    • 28
    • 29
    • 30
    • 31
    • 32
    • 33
    • 34
    • 35
    • 36
    • 37
    • 38
    • 39
    • 40
    • 41
    • 42
    • 43
    • 44
    • 45
    • 46
    • 47
    • 48
    • 49
    • 50
    • 51
    • 52
    • 53
    • 54
    • 55
    • 56
    • 57
    • 58
    • 59
    • 60
    • 61
    • 62
    • 63
    • 64
    • 65
    • 66
    • 67
    • 68
    • 69
    • 70
    • 71
    • 72
    • 73
    • 74
    • 75
    • 76
    • 77
    • 78
    • 79
    • 80
    • 81
    • 82
    • 83
    • 84
    • 85
    • 86
    • 87
    • 88
    • 89
    • 90
    • 91
    • 92
    • 93
    • 94
    • 95
    • 96
    • 97
    • 98
    • 99
    • 100
    • 101
    • 102
    • 103
    • 104
    • 105
    • 106
    • 107
    • 108
    • 109
    • 110
    • 111
    • 112
    • 113
    • 114
    • 115
    • 116
    • 117
    • 118
    • 119
    • 120
    • 121
    • 122
    • 123
    • 124
    • 125
    • 126
    • 127
    • 128
    • 129
    • 130
    • 131
    • 132
    • 133
    • 134
    • 135
    • 136
    • 137
    • 138
    • 139
    • 140
    • 141
    • 142
    • 143
    • 144
    • 145
    • 146
    • 147
    • 148
    • 149
    • 150
    • 151
    • 152
    • 153
    • 154
    • 155
    • 156
    • 157
    • 158
    • 159
    • 160
    • 161
    • 162
    • 163
    • 164
    • 165
    • 166
    • 167

    搭建后台项目环境:

    • npm init 初始化项目
    • 文件夹下出现 package.json即初始化成功
    • npm i nodemon -g 全局安装 这样修改后文件就可以帮助我们自动重启项目
    • npm i koa koa-router koa2-cors mysql -s
    • 封装 db.js 对连接数据库的函数进行模块封装
    • 使用 koa-router + mysql来编写接口
    • 使用 postman 来测试接口

    npm run dev 启动项目时会执行 package.json中 script 中 serve中的脚本

    {
      "name": "server",
      "version": "1.0.0",
      "description": "",
      "main": "index.js",
      "scripts": {
        "serve": "nodemon index.js",
        "test": "echo \"Error: no test specified\" && exit 1"
      },
      "keywords": [],
      "author": "",
      "license": "ISC",
      "dependencies": {
        "koa": "^2.13.4",
        "koa-bodyparser": "^4.3.0",
        "koa-router": "^12.0.0",
        "koa2-cors": "^2.0.6",
        "mysql": "^2.18.1"
      }
    }
    
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
  • 相关阅读:
    【Html——自由小球球】(效果+代码)
    C++项目实战-高并发服务器详析
    05方法的定义,调用重载
    【Node.js+koa--后端管理系统】设计标签创建、查询、接口 | 标签绑定到动态
    107.(前端)分类管理增加值实现——使用elementui中的动态编辑标签发送请求
    java-php-python-ssm虚拟银行业务培训游戏计算机毕业设计
    Java手写红黑树应用拓展案例
    深入理解多线程编程和 JVM 内存模型
    『Java安全』Shiro1.2.4反序列化漏洞(Shiro-550|CVE-2016-4437)复现与浅析
    c语言单元测试构建
  • 原文地址:https://blog.csdn.net/qyl_0316/article/details/127903797