egg.js基础入门

之前一直使用koa, 刚刚接触egg, 做了一些入门的笔记

准备工作

1  首先安装脚手架,,并创建项目。

 $ npm i egg-init -g
$ egg-init egg-demo --type=simple
$ cd egg-demo
$ npm i // 也可以使用yarn

2 . 启动项目

 $ npm run dev

浏览器打开http://127.0.0.1:7001/即可进入默认的首页。

3 . 项目目录

egg.js基础入门egg.js基础入门egg.js基础入门

   1 ) /app   ----------- 主要工作目录

      /controller   ------------- 控制器,比如获取service的数据和渲染view的模板

      /extend    ------------- 方法扩展,比如封装时间格式化方法

      /middleware  ----------- 中间件,比如登录权限设置

      /public   ------------ 静态文件目录,比如css,  js, image

      /service        ------------- 服务,操作数据库增删改查等

      /view     ------------- 模板目录,存放模板文件,如ejs, jade, pug, nunjucks等

      -router.js   ------------- 路由文件

     2 ) /config ---------- 主要配置目录

        -config.default.js  ------------ 配置文件,

      -plugin.js      ----------- 配置插件, 如开启模板引擎

开发阶段

1 . 新建路由

 # app/router.js

 module.exports = app => {
const { router, controller } = app;
router.get('/', controller.home.index); // 脚手架默认路由
router.get('/user', controller.user.index) // 新建路由
};

访问路径 http://127.0.0.1:7001/user时会指向controller.user.index控制器

controller是app应用的一个属性对象,直接指向controller目录,上面的controller.user.index表示,指向app/controller/user.js的index方法

2 . 新建控制器

# app/controller/user.js

 /* egg内置控制器 */
const Controller = require('egg').Controller; /*声明控制器类,并继承与Controller */
class UserController extends Controller {
/*声明异步方法*/
async index() {
/*ctx与koa中的一样,表示整个应用的上下文环境*/
const ctx = this.ctx;
ctx.body = '用户列表'
}
} module.exports = UserController;

3 . 新建服务

# app/service/user.js

 const Service = require('egg').Service;

 class UserService extends Service {
async findAll() {
/*这里暂时未从数据库获取数据,而是使用了静态数据填充*/
const users = [
{id: 1, name: '兰陵王'},
{id: 2, name: '程咬金'},
{id: 3, name: '诸葛亮'},
]
return users;
}
} module.exports = UserService;

5. 修改控制器(获取service中的数据, 并渲染到view的模板中)

  # app/controller/user.js

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

 class UserController extends Controller {
async index() {
const ctx = this.ctx;
// ctx.body = '用户列表'
const title = '用户列表';
const users = await ctx.service.user.findAll();
await ctx.render('user/index.ejs', {users: users, title})
}
} module.exports = UserController;

这里使用async..await作为异步获取,可以参考ES6教程,意思是users获取成功了,才会执行下一步。

使用ctx.render()渲染ejs模板, 并带有参数传递。

4 . 新建模板

  # app/view/user/index.ejs

 <!doctype html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport"
content="width=device-width, user-scalable=no, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Document</title>
</head>
<body>
<h2><%= title %></h2>
<ul>
<% users.forEach(function (item) { %>
<li><%= item.name %></li>
<% }) %>
</ul>
</body>
</html>

此时重启服务访问 http://127.0.0.1:7001/user会报错,原因是还没配置模板引擎。

5 . 安装并配置模板引擎

 $ yarn add egg-view-ejs
$ yarn add egg-view

# config/plugin.js

 module.exports = {
// had enabled by egg
static: {
enable: true,
},
// 开启ejs模板插件
ejs: {
enable: true,
package: 'egg-view-ejs',
}
}; // 简化形式 exports.key = value
// exports.ejs = {
// enable: true,
// package: 'egg-view-ejs'
// } // 函数形式
// module.exports = () => {
// return {
// ejs: {
//
// }
// }
// }

# config/config.default.js

 module.exports = appInfo => {
/*其他代码*/
config.view = {
// 设置ejs为默认的模板引擎
defaultViewEngine: '.ejs',
mapping: {
'.ejs': 'ejs'
}
};
/*其他代码*/
}

最后,重启服务器,并访问http://127.0.0.1:7001/user

egg.js基础入门

结束:

该入门还未连接数据库,如mongodb, mysql

上一篇:ubuntu 16.04 挂起后WiFi链接不上


下一篇:【深入ASP.NET原理系列】--ASP.NET页面生命周期