vue+mysql+egg.js 搭建后台服务(零基础 增删改查)

话不多说,先上图

目录

一、后台

二、前端(vuecli3 脚手架   iview ui)


一、后台

egg.js 中文官网

我这里用的是egg.js 脚手架搭建的

首先打开你要放的文件夹的位置,然后点击上面的路径cmd

$ mkdir egg-example && cd egg-example
$ npm init egg --type=simple
$ npm i
$ npm run dev
$ open http://localhost:7001

目录结构是这样的

首先我们用的是mysql  

$ npm i --save egg-mysql

package.json 

 // config/plugin.js

'use strict';
exports.mysql = {
  enable: true,
  package: 'egg-mysql',
};

 // config/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 + '_1612249951097_2119';

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

  // 配置与Mysql数据库的连接
  config.mysql = {
    // 数据库信息配置
    client: {
      // host
      host: 'localhost',
      // 端口号
      port: '3306',
      // 用户名
      user: 'root',
      // 密码
      password: '123456',
      // 数据库名
      database: 'localmysql',
    },
    // 是否加载到 app 上,默认开启
    app: true,
    // 是否加载到 agent 上,默认关闭
    agent: true,
  }


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

  return {
    ...config,
    ...userConfig,
  };
};

app/router.js

'use strict';

/**
 * @param {Egg.Application} app - egg application
 */
module.exports = app => {
  const { router, controller } = app;
  router.get('/', controller.home.index);
  router.get('/getUserList', app.controller.user.getUserList);//获取用户类表
  router.get('/getUserDetail', app.controller.user.getUserDetail);//获取用户详情
  router.post('/creatOrUpdata', app.controller.user.creatOrUpdata);//新建或者更新用户信息
  router.delete('/deleteUserById', app.controller.user.deleteUserById);//删除
};

 app/controller/user.js

// app/controller/user.js
const Controller = require('egg').Controller;
class UserController extends Controller {
    // 获取用户列表
    async getUserList() {
        const { ctx } = this;
        const result = await ctx.service.user.getUserList();
        ctx.body = result;
    }
    // 获取用户详情
    async getUserDetail() {
        const { ctx } = this;
        const result = await ctx.service.user.getUserDetail();
        ctx.body = result;
    }
    // 新建或者更新用户
    async creatOrUpdata() {
        const { ctx } = this;
        const result = await ctx.service.user.creatOrUpdata();
        ctx.body = result;
    }
    // 删除用户
    async deleteUserById() {
        const { ctx } = this;
        const result = await ctx.service.user.deleteUserById();
        ctx.body = result;
    }
}
module.exports = UserController;

 app/service/user.js

// app/service/user.js
const Service = require('egg').Service;
class UserService extends Service {
    // 获取列表
    async getUserList() {
        let { app } = this;
        let result = await app.mysql.query('select * from user');
        return {
            data: result,
        };
    }
    // 获取详情
    async getUserDetail() {
        let param = this.ctx.query
        let { app } = this;
        let result = await app.mysql.query('select * from user where id=?', param.id);
        return {
            data: result,
        };
    }
    // 新建或者编辑
    async creatOrUpdata() {
        let param = this.ctx.request.body
        let { app } = this;
        let result
        if (this.ctx.request.body.id) {
            if (app.mysql.query('select * from user where id=?', param.id)) {
                result = await app.mysql.update('user', param)  // 参数1:表名  参数2:数据
            } else {
                result = await app.mysql.insert('user', param)  // 参数1:表名  参数2:数据
            }
        } else {
            result = await app.mysql.insert('user', param)  // 参数1:表名  参数2:数据
        }
        return {
            data: result,
        };
    }
    // 删除用户
    async deleteUserById() {
        let param = this.ctx.query
        let { app } = this;
        let result = await app.mysql.delete('user', param)
        return {
            data: result,
        };
    }
}
module.exports = UserService;

问题:在我npm run dev 运行的时候我发现会报错,查了一下发现是因为数据库原因。解决连接:https://www.cnblogs.com/taohuaya/p/11401109.html

再次运行 http://127.0.0.1:7001/user 就有返回值了

因为Web 安全概念所以post请求中要传csrf 防范

官方文档:https://eggjs.org/zh-cn/core/security.html

解决连接:https://blog.csdn.net/qq_36763293/article/details/95061913

这里我们不做安全就是说访问不需要安全验证的下载依赖  npm i egg-security

在 config/config.default.js 

config.security = {
    xframe: {
      enable: false,
    },
    csrf: {
      enable: false,
    },
  };

然后就不设置安全了

二、前端(vuecli3 脚手架   iview ui)

  1. <template>
      <div class="home">
        <Button type="primary" @click="open">新建</Button>
        <Table
          width="550"
          border
          :columns="columns2"
          :data="data3"
          @on-ok="creatOrUpdata"
          @on-cancel="cancel"
        ></Table>
        <Modal v-model="modal1" title="详情">
          <Form ref="userForm" :model="userForm">
            <FormItem prop="user">
              <Input type="text" v-model="userForm.username" placeholder="Username">
                <Icon type="ios-person-outline" slot="prepend"></Icon>
              </Input>
            </FormItem>
          </Form>
          <div slot="footer">
            <Button type="error" size="large" @click="creatOrUpdata">确定</Button>
          </div>
        </Modal>
      </div>
    </template>
    
    <script>
    export default {
      name: "Home",
      components: {
        // HelloWorld
      },
      data() {
        return {
          columns2: [
            {
              title: "id",
              key: "id",
              fixed: "left",
            },
            {
              title: "名称",
              key: "username",
            },
            {
              title: "Action",
              key: "action",
              fixed: "right",
              width: 130,
              render: (h, params) => {
                return h("div", [
                  h(
                    "Button",
                    {
                      props: {
                        type: "text",
                        size: "small",
                      },
                      on: {
                        click: () => {
                          this.deleteUserById(params);
                        },
                      },
                    },
                    "删除"
                  ),
                  h(
                    "Button",
                    {
                      props: {
                        type: "text",
                        size: "small",
                      },
                      on: {
                        click: () => {
                          this.getUserDetail(params);
                        },
                      },
                    },
                    "编辑"
                  ),
                ]);
              },
            },
          ],
          data3: [],
          modal1: false,
          userForm: {
            id: null,
            username: null,
          },
        };
      },
      methods: {
        getUserList() {
          this.http.get("/api/getUserList").then((res) => {
            this.data3 = res.data.data;
          });
        },
        getUserDetail(data) {
          this.modal1 = true;
          let param = {
            id: data.row.id,
          };
          this.http.get("/api/getUserDetail", param).then((res) => {
            this.userForm = res.data.data[0];
          });
        },
        creatOrUpdata() {
          if (!this.userForm.id) {
            delete this.userForm.id;
          }
          let param = this.userForm;
          console.log(param, "param");
          this.http.post("/api/creatOrUpdata", param).then((res) => {
            this.modal1 = false;
            this.getUserList();
          });
        },
        deleteUserById(data) {
          let param = {
            id: data.row.id,
          };
          this.http.delete("/api/deleteUserById", param).then((res) => {
            this.getUserList();
          });
        },
        open() {
          this.modal1 = true;
          this.userForm.id = "";
          this.userForm.username = "";
        },
        cancel() {
          this.modal1 = false;
        },
      },
      mounted() {
        this.getUserList();
      },
    };
    </script>
    

三、数据库(id自增)

 

 

 

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

侧耳倾听...

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值