码迷,mamicode.com
首页 > 数据库 > 详细

node_egg项目搭建_注册写入数据库

时间:2020-03-21 09:19:56      阅读:35      评论:0      收藏:0      [点我收藏+]

标签:判断   post   success   接口   数据库名   agent   封装   inf   root   

├── app    
| ├── router.js
// 监听接口, 规定路由规则,承担执行动作的 Controller 的对应关系
│ ├── controller
      
| | └── home.js
// 将router请求(get,post..)分发到对应controller上, Controller 负责解析用户的输入,用对应的service方法处理业务,得到业务结果后封装并返回
│ ├── service

│ └── registerTools.js
// 保持 Controller 中的逻辑更加简洁,抽象出来的 Service 可以被多个 Controller 重复调用
│ ├── public

│ └── index.html
//发送请求
├── config

│ ├── config.default.js
// 默认配置信息
│ ├── plugin.js          // 插件配置信息

app/router.js

‘use strict‘;

/**
 * @param {Egg.Application} app - egg application
 */
module.exports = app => {
  const { router, controller } = app;
  router.post(‘/register‘, controller.home.register);
};

app/controller/home.js

‘use strict‘;

const Controller = require(‘egg‘).Controller;

class HomeController extends Controller {
  async register() {
    const { ctx } = this;
    const result = await ctx.service.registerTools.writeToDB();
    ctx.body = result;
  }
}
module.exports = HomeController;

app/service/registerTools.js

‘use strict‘;
const Service = require(‘egg‘).Service;
class RegisterTools extends Service {
  async writeToDB() {
    const { ctx } = this;
    // POST 的 body 应该使用 ctx.request.body,而不是 ctx.body。
    const data = ctx.request.body; // => {userId: ‘1021879494‘, userPassword: ‘123456‘, idCard: ‘5002002020‘}
    const result = await this.app.mysql.insert(‘register‘, data);
    // => INSERT INTO register (userId, userPassword, idCard) VALUES (‘1021879494‘, ‘123456‘, ‘5002002020‘)
    // 判断是否插入成功
    const insertSuccess = result.affectedRows === 1 ? { message: ‘success‘, status: ‘200‘ } : { message: ‘faid‘, status: ‘404‘ };
    return insertSuccess;
  }
}
module.exports = RegisterTools;

app/public/index.html

<!DOCTYPE html>
<html lang="zh-cn">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <script src="https://cdn.jsdelivr.net/npm/vue/dist/vue.js"></script>
  <script src="https://cdn.bootcss.com/axios/0.19.1/axios.min.js"></script>
  <title>Document</title>
</head>
<body>
  <div id="app">
    <h1>账号注册</h1>
    <form id="registerForm">
      用户名:<input type="text" name="userName" v-model="userInfo.userName"> <br>
      账号:<input type="text" name="userId" v-model="userInfo.userId"> <br>
      密码:<input type="text" name="password" v-model="userInfo.password"> <br>
      身份证:<input type="text" name="idCard" v-model="userInfo.idCard">
    </form>
    <button @click="handleRegister">注册</button>
  </div>
  <script>
    let vm = new Vue({
      el: #app,
      data: {
        userInfo: {
          userName: ‘‘,
          userId: ‘‘,
          password: ‘‘,
          idCard: ‘‘
        }
      },
      methods: {
        async handleRegister () {
          // post请求,传送参数,userInfo
          let result = await axios.post(/register, this.userInfo );
          console.log(result); // => {message: ‘success‘, status: ‘200‘}
        }
      }
    })
  </script>
</body>
</html>

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 + ‘_1584690783980_4916‘;

  // 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: ‘root‘,
      // 密码
      password: ‘123456‘,
      // 数据库名
      database: ‘userdatabase‘,
    },
    // 是否加载到app上,默认开启,
    app: true,
    // 是否加载到agent上,默认关闭
    agent: false,
  };
  // post请求安全规范
  config.security = {
    csrf: {
      enable: false,
    },
  };

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

config/plugin.js

‘use strict‘;

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

 

node_egg项目搭建_注册写入数据库

标签:判断   post   success   接口   数据库名   agent   封装   inf   root   

原文地址:https://www.cnblogs.com/JunLan/p/12536290.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有 京ICP备13008772号-2
迷上了代码!