首页 > 其他分享 >egg

egg

时间:2022-10-20 00:24:23浏览次数:63  
标签:false egg app ctx type config

安装

$ mkdir 创建目录 && cd 创建目录 $ npm init egg --type=simple $ npm i

网址

    // 使用post 会报 csrf token 问题   
    //   安装 : npm i egg-cors - save
    //   配置插件
    //   config/plugin.js
    // 跨域的插件
    cors: {
        enable: true,
        package: 'egg-cors'
    }
          

// config/config.default.js // 关闭csrf 开启跨域 config.security = { // 关闭csrf csrf: { enable: false }, //跨域白名单 domainWhiteList: ['http://127.0.0.1:8080'] }; // 允许跨域的方法 config.cors = { origin: '*', allowMethods: 'GET,PUT,POST,DELETE,PATCH' };

ctx

获取url问号get传值参数  :   this.ctx.query   获取:id 传递过来的参数  :  this.ctx.params   获取post请求传递的参数 : this.ctx.request.body   修改状态码   :   this.ctx.status  

创建数据库和数据表

  操作数据库和表  ==> 叫做模型
// app/model/user.js
'use strict';

module.exports = (app) => {
    const { INTEGER, STRING, DATE, ENUM } = app.Sequelize;

    // 配置(重要:一定要配置详细,一定要!!!)
    const User = app.model.define('user', {
        id: {
            type: INTEGER(20).UNSIGNED,
            primaryKey: true,  //主键
            autoIncrement: true //自增
        },
        username: {
            type: STRING(30),
            allowNull: false, //不允许为空
            defaultValue: '', //默认值为空
            comment: '用户名称', //备注用户名
            unique: true //唯一性
        },
        password: {
            type: STRING(200),
            allowNull: false,
            defaultValue: '',
        },
        avatar_url: {
            type: STRING(200),
            allowNull: false,
            defaultValue: '',
        },
        sex: {
            type: ENUM,
            values: ['男', '女', '保密'],
            allowNull: false,
            defaultValue: '男',
            comment: '用户性别',
        },
        created_at: DATE,
        updated_at: DATE,
    });

    return User;
};

这个 Model 就可以在 Controller 和 Service 中通过 app.model.User 或者 ctx.model.User 访问到了

     

标签:false,egg,app,ctx,type,config
From: https://www.cnblogs.com/qd-lbxx/p/16806406.html

相关文章