On the Node.js framework: eggjs (environment with papers)

eggjs is an excellent framework for Node.js

Overview: Why eggjs is an excellent Node.js framework (skippable) on the title?

In other words, why do we choose eggjs development framework rather than using Express beginner before it?

 

  Express is the most famous Node.js framework, it is even the only official had recommended (currently)

  However, according to the actual development, I think it's quite a lengthy configuration, for example: it can be a app.use () covered up dozens of lines

  This is, I can not go on using it, so it stopped learning.

 

To configure terms: eggjs done well, it is through the development constraints, all the configuration files in the config file.

At first it one by one when you load the server settings will be overwritten after the previous set. Json similar configuration is based on the same wording, which allows us to easily locate a place to configure and modify it (because key can not be repeated, will know where to retrieve a)

 

The same, eggjs has a large number of plug-ins, developers need what kind of features, almost all can be found on the official plugin.

If you do not find the plug-in, eggjs also supports customization.

Here you can find and use the official API Documentation: https://eggjs.org/zh-cn/

 

No longer say, let's start a project framework eggjs it (with official somewhat different, according to the official quick start, always encountered inexplicable error)

The official errors, configuration I spent three or four hours to use the framework to really understand, and I hope you read this article, just half an hour to write a high quality project

 

1.1 scaffolding establish preliminary engineering directory

This step is all based on one of the essential aspects of Node.js works: Of course, you can also create manually.

Open DOS / terminal, use the following command to change to the project where you need to store the (here is my project storage location):

 

cd C:\Users\chong\Documents\NodeJS

 

I created a directory NodeJS in the "Documents" under Windows, it will be for me the root of all Node project.

Create a project folder and enter (project is the project name, you can change):

mkdir project && cd project

 

Here, we initialize the scaffolding and installation and start-dependent:

# Initialize directory (creates the necessary folders and JS, package.json file) 
--type the init = npm the Simple Egg
# installation depends npm i

 

Time to perform the initialization directory, you need to fill out some information that will eventually import package.json profile.

 

 

 

 

Red box is created during initialization of eggjs files and folders, follow-up we come to understand their role [important]

The arrow points to is the need to fill in information such as project name, a description, author and Cookie key

 

Now, you've got a more complete directory structure (I've run a few times, than just created more than a few files, do not care):

 

 

Well, then start the project, there are several ways to start:

# Start the project 
npm RUN dev

npm Start

 

npm start belong to a production environment use, this way, then, need to print information output to the console to see it.

The npm run dev is the development of the recommended start-up mode, when you modify the code, you do not need to manually restart the server, eggjs restart on their own, you only need to wait for a while you can see the corresponding changes in the browser.

Important: You can always write console.log in the code, the console will have a corresponding display.

 

Below is a variety of start-up or test command (package.json), are added in front of the npm can be used.

也可以修改它们,如果你需要换个端口,例如 dev,修改为 egg-bin dev --port 8081 (注意:两个 - 符号)

 

 

 

启动完成后,在浏览器中访问 DOS / 终端 显示的路径(红色箭头):

 

 

 

黄色部分是被修改的文件,在这里不必理会。

到这里,你的初始化工作已经做完,不妨休息会,再继续往下阅读。

 

 

1.2 了解各个目录、文件的作用以及 eggjs 如何处理它们

相信你已经成功初始化了吧,现在让我们来了解 eggjs 的目录结构,各个文件的作用:

重新回到之前的一张图,我们可以清晰地看见 eggjs 到底创建了什么。

 

 

 

前一些以 . 开头的文件我们不必理会,从 package.json 文件开始(我们已经知道这是配置文件),往下看:

它创建了两个文件夹,分别是: app、config (test 属于测试,如单元测试等,我们也不必理会)

 

app 是网站处理用户请求,以及浏览器请求服务器资源的应用文件夹

它包含:router(路由文件)、controller(处理器)

是的,初始化就这么两个,所以我建议在 app 目录下再手动创建以下几个文件夹:

 

public(存放静态资源,如 css、js、img)

view (存放视图文件)

service(处理数据等业务操作)

 

先来详细说说路由文件,所有的网站都会有一个访问地址,路由则是客户端首先进入位置:

 

 

客户端(浏览器)会发送一个请求,这个请求将会首先进入路由分发文件,匹配成功到某一个 处理器(Controller)后

这个处理器将会去进行相关业务操作(Service)拿到数据,之后 view 渲染一个页面成功后一层层返还回去。

 

controller 文件夹下则放置着我们所有核心的网站代码(后续解释)

 

任何一个网站都需要进行配置,而所有的 Web服务器 都应该自身有创建环境的能力,而不是人为去为这个服务器配置好环境。

那么 config 文件夹就是为此而生。

 

由前面得知:eggjs 有着丰富的插件,所以必然有一个插件的管理、配置文件,它就是 plugin.js 

后续我们将知道一个插件应该怎样启用,关闭,安装,这里先不说明;

 

eggjs 最重要的配置文件则是 :config.default.js,它管理着整个 Node服务器 的所有配置,包括插件、Cookie安全密钥、视图渲染等等配置。

 

好了,看到这里你已经对生成的 eggjs 项目工程有了一个大致的了解(我昨天才接触 node.js ,若有不对,望在评论中指出,我会进行修改,多谢)

 

1.3  了解一个请求是如何被处理的【重要】

读完前面,你已经明白:eggjs 工程中的目录,文件的作用(只介绍了部分),现在让我们来深入了解代码层次上,eggjs 如何处理用户请求(不解析源码,从生成的文件来看):

 

先来了解路由文件怎样工作(建议所有的路由设计都放在一个文件中):

'use strict';

/**
 * @param {Egg.Application} app - egg application
 */
module.exports = app => {
    
    const { router, controller } = app;

    router.get('/', controller.main.index);
};

 

router.get() 方法指的是 GET 请求。

第一个参数表示 URL,例如 www.cnblogs.com 是域名,那么 www.cnblogs.com/index 中的  / 开始,则都是该网站下的‘路由’

第二个参数表示 controller 文件夹下的 main.js 中的 index 方法【重要】,如下:

'use strict';

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

class MainController extends Controller {
    async index() {
        this.ctx.body = '<h1>Hello world</h1>';
    }
}

module.exports = MainController;

 

所以,你会在浏览器的窗口中看见:

 

 

看,你已经知道它的请求过程了!先在 router.js 文件中找到用户请求的位置,而网站进入默认是 / 

所以我们已经捕获到了这次请求,之后根据路由文件的描述找到 controller 文件夹下的 main 文件,在从中检索到 index 方法

这个方法设置了body,让它输出一个 h1 标签,写上 Hello world 。

 

router -> controller.main.index() 

 

但是这样的网站根本不具备使用能力,留不住用户,我们还需要根据不同用户数据,渲染一个好看的页面给用户。

这时,我们就可以知道 eggjs 插件的强大之处了(再缓缓,梳理下阅读到的知识,准备好了再继续了解吧)。

 

 

1.4 通过模板引擎渲染页面

eggjs 强大的插件足以使你在 Node服务器 上做到与其它Web服务器不同的体验

先述说模板引擎,之后,让我们了解一下网站多语言一键配置。

 

以 Nunjucks 模板引擎为例:

首先引入两个插件:egg-view、egg-view-nunjucks

npm i egg-view -save

npm i egg-view-nunjucks -save

 

之后打开 config/config.default.js 文件:

'use strict';

const path = require('path');


module.exports = appInfo => {
    return {
        // Cookie 安全密钥
        keys: "_skfhj8546542354.16554",
        // 项目日志存放文件夹
        logger: {
            dir: path.join(appInfo.baseDir, 'logs'),
        },
        // 渲染模板配置
        view: {
            // 配置视图根路径
            root: path.join(appInfo.baseDir, 'app/view'),
            // 是否缓存路径
            cache: true,
            // 配置文件默认扩展名
            defaultExtension: '.nj',
            // 默认渲染模板引擎
            defaultViewEngine: 'nunjucks',
            // 文件映射配置
            mapping: {
                '.nj': 'nunjucks'
            }
        }
    };
};

 

我已经注明了各个属性的作用,可复制到你的文件中。

之后启用插件:egg-view-nunjucks,打开 config/plugin.js 文件

'use strict';


/**
 * 模板引擎:用于渲染页面数据
 */
exports.nunjucks = {
    enable: true,
    package: 'egg-view-nunjucks',
};

 

配置方面已经准备完毕,之后需要在 app/view 目录下创建一个 index.nj 模板文件

<html>
    <head>
        <title>{{ page_title }}</title>
    </head>
    <body>
        <h1>{{ page_content }}</h1>
    </body>
</html>

 

双括号是模板引擎的语法之一,还有循环等(是不是觉得跟 jsp 差不多)

好了,让我们修改 controller/main.js 文件

'use strict';

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

class MainController extends Controller {
    async index() {
        const { ctx } = this;
        
        await ctx.render('index',{
            page_title : "标题",
            page_content : "模板引擎所渲染的页面"
        });
    }
}

module.exports = MainController;

 

注意:请加上 await 关键字,它表示等待一个 Promise 对象,如果不加上,会出现 404 错误,

因为在渲染过程中,处理器却返回了结果(没数据的结果),自然客户端也会认为服务器没有找到资源。

 

 

 

 

 

现在已经跟我们所想的一致,那么到这里,你已经具备了开发一个项目的能力;

之后会逐步介绍数据库连接,数据处理等方法。敬请期待。

 

 

1.4.1  多语言配置(将会引用一些官方例子)

多语言显示(按需配置),很简单,基于插件扩展能力,我们首先在 config.default.js 中增加配置,完整看起来是这个样子的:

'use strict';

const path = require('path');


module.exports = appInfo => {
    return {
        // Cookie 安全密钥
        keys: "_tourism_2650159865482545.265",
        // 项目日志存放文件夹
        logger: {
            dir: path.join(appInfo.baseDir, 'logs'),
        },
        // 渲染模板配置
        view: {
            // 配置视图根路径
            root: path.join(appInfo.baseDir, 'app/view'),
            // 是否缓存路径
            cache: true,
            // 配置文件默认扩展名
            defaultExtension: '.qyml',
            // 默认渲染模板引擎
            defaultViewEngine: 'nunjucks',
            // 文件映射配置
            mapping: {
                '.qyml': 'nunjucks'
            }
        },
        // 多语言配置
        i18n: {
            // 默认语言,默认 "en_US"
            defaultLocale: 'zh-CN',
            // URL 参数,默认 "locale"
            queryField: 'locale',
            // Cookie 记录的 key, 默认:"locale"
            cookieField: 'locale',
            // Cookie 的 domain 配置,默认为空,代表当前域名有效
            cookieDomain: '',
            // Cookie 默认 `1y` 一年后过期, 如果设置为 Number,则单位为 ms
            cookieMaxAge: '1y',
        }
    };
};

最新版的 eggjs 中默认开启多语言插件,所以我们不必手动启用。

 

之后在 config 目录下创建一个 locale 文件夹【重要:拼写一定要正确】

在 locale 文件夹中创建所需配置的语言文件(图仅示例两种),可以是 JSON 文件,也可以是 JS 文件,大概是这样的(我的是 JS 格式):

 

 

 

所有的多语言开发都会基于一种语言,我以英语为例(国际化也都是英语):

zh-CN.js 是这样配置的(用官方的例子):

module.exports = {
  "Email": "邮箱",
  "Welcome back, %s!": "欢迎回来,%s!"
};

 

如果你是基于 JSON 文件,也就是 zh-CN.json ,那么编写是这个样子的:

{
  "Email": "邮箱",
  "Welcome back, %s!": "欢迎回来,%s!"
}

 

就算是英语也需要配置:

en_US.js 会是这样编写的:

module.exports = {
  "Email": "Email",
  "Welcome back, %s!": "Welcome back,%s!"
};

 

至于 %s %d 之类的 format 标识,它们的作用是这样的(引用官方例子):

// config/locale/zh-CN.js
module.exports = {
  'Welcome back, %s!': '欢迎回来,%s!',
};

ctx.__('Welcome back, %s!', 'Shawn');
// zh-CN => 欢迎回来,Shawn!
// en-US => Welcome back, Shawn!

 

好了,一切准备就绪,如果需要在 Controller 中直接输出,需要调用 __ 方法进行转义,注意是两个下斜杠,不是让你填空...

class HomeController extends Controller {
  async index() {
    const ctx = this.ctx;
    ctx.body = {
      message: ctx.__('Welcome back, %s!', ctx.user.name)
      // 或者使用 gettext,gettext 是 __ 函数的 alias
      // message: ctx.gettext('Welcome back', ctx.user.name)
      user: ctx.user,
    };
  }
}

 

在视图模板中这样使用,假设你是 nunjucks 模板引擎:

<html>
    <head>
        <title>{{ page_title }}</title>
    </head>
    <body>
        <h1>{{ __('Welcome back, %s!', page_content) }}</h1>
    </body>
</html>

 

经过处理后,我们将得到这样的页面效果:

 

 

现在你也可以开发一个支持多语言的网站了,我所示例的都是基础代码,关于多语言支持请参考以下网址:

https://eggjs.org/zh-cn/core/i18n.html

 

今天就到这里了,后续会出一些插件使用,或者是可以快速开发的方法。

 

 

 

2020-2-11 写于揭阳

转载请附上本博客地址:https://www.cnblogs.com/chongsaid/ 或当前文章链接,否则视为侵犯著作权。

Guess you like

Origin www.cnblogs.com/chongsaid/p/nodejs_eggframe_getStart.html