egg+vue+mysql simply implements the addition, deletion, and modification functions

1. Install vue and egg

vue create web-app
npm init egg --type=simple --registry https://registry.npm.taobao.org

The generated directory is as follows:
Insert image description here
server-app stores the egg framework and
web-app stores the vue framework.

2. Plug-in installation and configuration

web-app

cd web-app
npm i axios
npm i vue-router
npm i element-ui 
npm i less

axios configuration (configure api.js and config.js under network)
Insert image description here
api.js (stores the method of connecting the front end to the back end)

import axios from 'axios'

export default {
    
    
    getList: (data) => axios.get('/api/getList', data),
    addList: (data) => axios.post('/api/addList', data),
    updataList: (data) => axios.post('/api/updataList', data),
    deleteList: (data) => axios.post('/api/deleteList', data),
}

config.js (encapsulated axios)

import axios from "axios";
axios.defaults.timeout = 5000; //超时时间设置
axios.defaults.withCredentials = true; //true允许跨域
//Content-Type 响应头
axios.defaults.headers.post["Content-Type"] =
    "application/x-www-form-urlencoded;charset=UTF-8";
let token = localStorage.getItem('authorization');
axios.defaults.headers.post["authorization"] = token;
if (process.env.NODE_ENV === "production") {
    
    
    /*第二层if,根据.env文件中的VUE_APP_FLAG判断是生产环境还是测试环境*/
    if (process.env.VUE_APP_FLAG === "pro") {
    
    
        //production 生产环境
        axios.defaults.baseURL = "http://127.0.0.1:7002"; //根据本机的egg运行的路径设置
    } else {
    
    
        //test 测试环境
        axios.defaults.baseURL = "";
    }
} else {
    
    
    //dev 开发环境
    axios.defaults.baseURL = "http://127.0.0.1:7002";//根据本机的egg运行的路径设置
}

// 响应拦截器
axios.interceptors.response.use(
    response => {
    
    
        // 如果返回的状态码为200,说明接口请求成功,可以正常拿到数据
        // 否则的话抛出错误
        if (response.status === 200) {
    
    
            return Promise.resolve(response);
        } else {
    
    
            return Promise.reject(response);
        }
    },
    // 服务器状态码不是2开头的的情况
    error => {
    
    
        if (error.response.status) {
    
    
            switch (error.response.status) {
    
    
                // 401: 未登录
                case 401:
                    router.replace({
    
    
                        path: "/login",
                        query: {
    
    
                            redirect: router.currentRoute.fullPath
                        }
                    });
                    break;
                case 403:
                    this.$message("管理员权限已修改请重新登录");
                    // 清除sessionStorage
                    // store.commit("qiut");
                    // 跳转登录页面,并将要浏览的页面fullPath传过去,登录成功后跳转需要访问的页面
                    setTimeout(() => {
    
    
                        router.replace({
    
    
                            path: "/login",
                            query: {
    
    
                                redirect: router.currentRoute.fullPath
                            }
                        });
                    }, 1000);
                    break;

                    // 404请求不存在
                case 404:
                    this.$message("请求页面飞到火星去了");
                    break;
            }
            return Promise.reject(error.response);
        }
    }
);

/**
 * 封装get方法
 * @param url
 * @param data
 * @returns {Promise}
 */

export function get(url, params = {
    
    }) {
    
    
    return new Promise((resolve, reject) => {
    
    
        axios
            .get(url, {
    
    
                params: params
            })
            .then(response => {
    
    
                resolve(response.data);
            })
            .catch(err => {
    
    
                reject(err);
            });
    });
}

/**
 * 封装post请求
 * @param url
 * @param data
 * @returns {Promise}
 */

export function post(url, data = {
    
    }) {
    
    
    return new Promise((resolve, reject) => {
    
    
        axios.post(url, data).then(
            response => {
    
    
                resolve(response.data);
            },
            err => {
    
    
                reject(err);
            }
        );
    });
}

/**
 * 封装delete请求
 * @param url
 * @param data
 * @returns {Promise}
 */

export function deletes(url, data = {
    
    }) {
    
    
    return new Promise((resolve, reject) => {
    
    
        axios.delete(url, data).then(
            response => {
    
    
                resolve(response.data);
            },
            err => {
    
    
                reject(err);
            }
        );
    });
}

/**
 * 封装put请求
 * @param url
 * @param data
 * @returns {Promise}
 */

export function put(url, data = {
    
    }) {
    
    
    return new Promise((resolve, reject) => {
    
    
        axios.put(url, data).then(
            response => {
    
    
                resolve(response.data);
            },
            err => {
    
    
                reject(err);
            }
        );
    });
}

Introduced in main.js

import Vue from 'vue'
import App from './App.vue'
import ElementUI from 'element-ui';
import 'element-ui/lib/theme-chalk/index.css';
import router from './router'
import './network/config'
import api from './network/api'

Vue.use(ElementUI);
Vue.config.productionTip = false
Vue.prototype.$api = api //全局注入

new Vue({
    
    
  router,
  render: h => h(App),
}).$mount('#app')

view page method

   //删除
   async deleteList(id){
    
    
      const params = {
    
    };
      params["id"] = id;
      let {
    
     data } = await this.$api.deleteList(params);
      if (data.code !== 200) {
    
    
        return this.$message.error(data.data);
      }
      this.$message.success(data.data);
      await this.getList();
    },
    //修改
   async updataList(){
    
    
      let {
    
     data } = await this.$api.updataList(this.form);
      if (data.code !== 200) {
    
    
        return this.$message.error(data.data);
      }
      this.$message.success(data.data);
      this.dialogVisible = false
      await this.getList();
    },
    //修改得到当前id
    showEdit(item){
    
    
      this.dialogVisible = true
      this.form = JSON.parse(JSON.stringify(item))
    },
    //获取全部数据
    async getList() {
    
    
      let {
    
     data } = await this.$api.getList();
      this.list = data.data;
    },
    //增加
    async addList() {
    
    
      const params = {
    
    };
      params["username"] = this.username;
      params["email"] = this.email;
      params["message"] = this.message;
      let {
    
     data } = await this.$api.addList(params);
      if (data.code !== 200) {
    
    
        return this.$message.error(data.data);
      }
      this.$message.success(data.data);
      await this.getList();
    },

server-app

cd server-app
npm i egg-mysql
npm i egg-cors

Insert image description here

plugin.js

'use strict';

/** @type Egg.EggPlugin */
module.exports = {
    
    
  // had enabled by egg
  // static: {
    
    
  //   enable: true,
  // }
  mysql: {
    
    
    enable: true,
    package: 'egg-mysql',
  },
  cors: {
    
    
    enable: true,
    package: 'egg-cors',
  },
};

config.default.js

/* eslint valid-jsdoc: "off" */

'use strict';

/**
 * @param {Egg.EggAppInfo} appInfo app info
 */
module.exports = appInfo => {
    
    
  /**
   * built-in config
   * @type {Egg.EggAppConfig}
   **/
  const config = exports = {
    
    };

  // use for cookie sign key, should change to your own and keep security
  config.keys = appInfo.name + '_1643251211068_3905';

  // add your middleware config here
  config.middleware = [];

  // add your user config here
  const userConfig = {
    
    
    // myAppName: 'egg',
  };

  config.mysql = {
    
    
    // 单数据库信息配置
    client: {
    
    
      // host
      host: 'localhost',
      // 端口号
      port: '3306',
      // 用户名
      user: '用户名',
      // 密码
      password: '密码',
      // 数据库名
      database: '数据库名',
    },
    // 是否加载到 app 上,默认开启
    app: true,
    // 是否加载到 agent 上,默认关闭
    agent: false,
  };
  config.security = {
    
    
    csrf: {
    
    
      enable: false,
      ignoreJSON: true,
    },
    domainWhiteList: [ 'http://localhost:8081' ], //前端服务路径
  };

  config.cors = {
    
    
    origin: 'http://localhost:8081',//前端服务路径
    credentials: true,//解决跨域问题
    allowMethods: 'GET,HEAD,PUT,POST,DELETE,PATCH,OPTIONS',
  };
  return {
    
    
    ...config,
    ...userConfig,
  };
};

router.js

'use strict';

/**
 * @param {Egg.Application} app - egg application
 */
module.exports = app => {
    
    
  const {
    
     router, controller } = app;
  router.get('/', controller.home.index);
  router.get('/api/getList', controller.indexController.getList);
  router.post('/api/addList', controller.indexController.addList);
  router.post('/api/updataList', controller.indexController.updataList);
  router.post('/api/deleteList', controller.indexController.deleteList);
};

indexController.js

'use strict';
const Controller = require('egg').Controller;
class indexController extends Controller {
    
    
  async getList() {
    
    
    const res = await this.ctx.service.indexService.getList();
    this.ctx.body = res;
  }
  async addList() {
    
    
    const params = this.ctx.request.body;
    const res = await this.ctx.service.indexService.addList(params);
    this.ctx.body = res;
  }
  async updataList() {
    
    
    const params = this.ctx.request.body;
    const res = await this.ctx.service.indexService.updataList(params);
    this.ctx.body = res;
  }
  async deleteList() {
    
    
    const params = this.ctx.request.body;
    const res = await this.ctx.service.indexService.deleteList(params);
    this.ctx.body = res;
  }
}
module.exports = indexController;

indexService.js

'use strict';
const Service = require('egg').Service;
class indexService extends Service {
    
    
  async getList() {
    
    
    const res = await this.app.mysql.select('表名');
    if (!res) {
    
    
      return {
    
    
        code: 400,
        data: [],
        msg: 'error',
      };
    }
    return {
    
    
      code: 200,
      data: res,
      msg: 'success',
    };
  }
  async addList(params) {
    
    
    const res = await this.app.mysql.insert('表名', {
    
    
      username: params.username,
      email: params.email,
      message: params.message,
      time: new Date(),
    });
    if (res.affectedRows !== 1) {
    
    
      return {
    
    
        code: 400,
        data: '创建失败',
      };
    }
    return {
    
    
      code: 200,
      data: '创建成功',
    };
  }
  async updataList(params) {
    
    
    const res = await this.app.mysql.update('表名', {
    
    
      id: params.id,
      username: params.username,
      email: params.email,
      message: params.message,
      time: new Date(),
    });
    if (res.affectedRows !== 1) {
    
    
      return {
    
    
        code: 400,
        data: '修改失败',
      };
    }
    return {
    
    
      code: 200,
      data: '修改成功',
    };
  }
  async deleteList(params) {
    
    
    const res = await this.app.mysql.delete('表名', {
    
    
      id: params.id,
    });
    if (res.affectedRows !== 1) {
    
    
      return {
    
    
        code: 400,
        data: '删除失败',
      };
    }
    return {
    
    
      code: 200,
      data: '删除成功',
    };
  }
}
module.exports = indexService;

3. mysql field

Insert image description here

4. Start the project

cd web-app
npm dev
cd server-app
npm serve

Guess you like

Origin blog.csdn.net/qq_42048638/article/details/122719516