之前一直使用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 . 项目目录

   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

结束:

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

egg.js基础入门的更多相关文章

  1. JS基础入门篇(三十五)—面向对象(二)

    如果没有面向对象这种抽象概念的小伙伴,建议先看一下我写的JS基础入门篇(三十四)-面向对象(一)

  2. JS基础入门篇(二十七)—BOM

    虽然上次写到js基础篇(二十四),这次直接写到(二十七).是为了提醒自己中间有几篇没写.特此说明一下啊. 1.window.open() 使用a标签呢,点击一下a标签页面才会跳转,有时候我们需要做的操 ...

  3. Nuxt.js 基础入门教程

    原文链接 Vue 开发一个单页面应用,相信很多前端工程师都已经学会了,但是单页面应用有一个致命的缺点,就是 SEO 极不友好.除非,vue 能在服务端渲染(ssr)并直接返回已经渲染好的页面,而并非只 ...

  4. JS基础入门篇(六)— 数据类型

    1.数据类型 数据类型:我感觉就是对数据的种类进行分类.就好比把人分为儿童,青少年,中年,老年一样. 基础数据类型: Number(数字),String(字符串),Null(空),Undefined( ...

  5. Underscore.js基础入门

    公司产品集成了对Underscore.js,所以需要对这个库有一定的了解.通过查阅资料,发现这个库主是对Array和JSON的处理支持.通过Underscore.js库,可以方便的对Array和JSO ...

  6. gulp.js基础入门

    安装 Node 去 nodejs.org 根据系统选择性按照教程安装Node. 创建项目 创建项目文件夹 进入项目文件夹 初始化项目 使用npm命令:npm init,根据提示完成. 安装 Gulp ...

  7. JS 基础 入门

    JS做弹窗效果 //单行注释/*多行注释*/// 网页 标签语言    js语言是脚本语言/* 数据类型: 容器 1.整型  (int)  2.小数类型: float: 单精度的小数: double: ...

  8. JS基础——入门必备

    ·首先,来简单的说一下,JS是啥,JS是JavaScript的简写,是 基于浏览器的 基于对象的 事件驱动 脚本语言 ·那么JS有什么用呢?ta可以实现: 表单验证 添加动画效果 动态更改页面内容 A ...

  9. React.js基础入门

    本文主要是针对React的一些demo教程.参考了菜鸟教程中的react教程,做了一些总结.Demo的下载链接是 https://github.com/RealAndMe/react-demo 下面要 ...

随机推荐

  1. C语言 结构体中的零长度数组

    /* C语言零长度数组大小和取值问题 */ #include <stdio.h> #include <stdlib.h> #include <string.h> s ...

  2. DirectX using C++_error X3539:ps1_x is no longer supported...解决方案

    问题来源 在研究HLSL时编译一个demo出现了error X3539的问题 解决方案 将代码中的ps_1_1 改为ps_2_0 PixelShader = compile ps_1_1 PS(); ...

  3. mac安装Redis可视化工具-Redis Desktop Manager

    Redis是一个超精简的基于内存的键值对数据库(key-value),一般对并发有一定要求的应用都用其储存session,乃至整个数据库.不过它公自带一个最小化的命令行式的数据库管理工具,有时侯使用起 ...

  4. Linux 正则表达式_010

    Linux 正则表达式 标注:本教程只针对linux运维的三剑客命令awk,sed,grep正则表达式 什么是正则表达式? 简单的说,正则表达式就是为处理大量的字符串而定义的一套规则和方法通过定义的这 ...

  5. 为什么不应该使用Zookeeper做服务发现?(转载)

    转载自: http://dockone.io/article/78 [编者的话]本文作者通过ZooKeeper与Eureka作为Service发现服务(注:WebServices体系中的UDDI就是个 ...

  6. SpringCloud(一)浅谈SpringCloud

    前言 现在微服务实在是太火了,所以我们必不可少的是要学习一下SpringCloud了,服务化的核心就是将传统的一站式应用 根据业务拆分成一个一个的服务,而微服务在这个基础上要更彻底地去耦合(不再共享D ...

  7. there was an error running the selected code generator unable to retrieve metadata for

    there was an error running the selected code generator unable to retrieve metadata for PROBLEM: I ha ...

  8. 超简单C#获取带汉字的字符串真实长度(单个英文长度为1,单个中文长度为2)

    https://blog.csdn.net/u014732824/article/details/84952848 int i = System.Text.Encoding.Default.GetBy ...

  9. google的python语言规范

    Python语言规范   Lint Tip 对你的代码运行pylint 定义: pylint是一个在Python源代码中查找bug的工具. 对于C和C++这样的不那么动态的(译者注: 原文是less ...

  10. MySQL建表、插入语句等

    不定时更新MySQL的一些基础语句以及出现过的问题 5.10 建表语句 CREATE TABLE `policy_landvalue` ( `id` ) NOT NULL AUTO_INCREMENT ...