egg.js入门--创建模版

egg.js 的模版创建 egg.js 官网:https://www.eggjs.org/zh-CN/ 1. 检查 nodejs 版本,这里推荐 18 版本以上;按照官网的要求还要:npm >= 6.1.0 2. 创建项目: npm init egg --type=simple npm i 3.

egg.js 的模版创建

egg.js 官网:https://www.eggjs.org/zh-CN/

1. 检查 nodejs 版本,这里推荐 18 版本以上;按照官网的要求还要:npm >= 6.1.0

2. 创建项目:

npm init egg --type=simple
npm i

3. 添加插件:

yarn add egg-mysql egg-router-plus egg-jwt

egg-sql:用来操作 mysql

egg-router-plus:自动加载路由文件、命名空间管理和便捷的重定向功能等

egg-jwt:生成 token

4. 配置 config.default.js

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

 /**
  * @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 + "";

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

   // add your user config here
   const userConfig = {
     // myAppName: 'egg',
   };
   config.cluster = {
     listen: {
       path: "",
       port: 8000,
       hostname: "0.0.0.0", // 0.0.0.0
     },
   };

   //mysql配置
   config.mysql = {
     // 单数据库信息配置
     client: {
       // host
       host: "",
       // 端口号
       port: "",
       // 用户名
       user: "",
       // 密码
       password: "",
       // 数据库名
       database: "",
     },
     app: true,
     agent: false,
   };

   // 登录
   config.jwt = {
     secret: "", //自定义token的加密条件字符串,可按各自的需求填写
   };

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

5. 配置 plugin.js

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

至此,项目的大体框架已经搭建完成,eggjs作为一个基于koa的框架,在开发CRUD的接口方面有着极大的优势,但让的缺点也很明显,很多中间件都需要自行开发,比如jwt、文件上传等。

LICENSED UNDER CC BY-NC-SA 4.0
Comment