0
点赞
收藏
分享

微信扫一扫

Egg.js(一):安装、模版引擎、路由配置


安装 && 启动

$ mkdir egg-example && cd egg-example
$ npm init egg --type=simple
$ npm i
$ npm run dev
$ open

目录结构

Egg.js(一):安装、模版引擎、路由配置_nodejs

MVC

  • model 处理数据请求、操作数据库
  • view 视图层
  • controller 数据逻辑层

配置路由 && 获取传值

// app/controller/add.js
// demoURL: http://127.0.0.1:7001/add/1,2,3?name=Lee
'use strict';

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

class AddController extends Controller {

async index() {

const {
ctx
} = this;

ctx.body = [
ctx.params, // 获取动态路由传值
ctx.query // 获取query地址栏传值
];

}

}

module.exports = AddController;

// app/router.js
/* CODE */
router.get('/add/:id', controller.add.index);
/* CODE */

配置模版引擎

npm i egg-view-ejs --save

  • 1.配置​​config/plugin.js​

exports.ejs = {
enable: true,
package: 'egg-view-ejs',
};

  • 2.配置​​config/config.default.js​

exports.view = {
mapping: {
'.ejs': 'ejs',
},
};
// or
module.exports = appInfo => {
/* CODE */
// add your user config here
const userConfig = {
view: {
mapping: {
'.html': 'ejs', // 后缀名 用 ejs 解析 .html 文件
}
}
};
/* CODE */
return {
/* CODE */
...userConfig,
};

};

  • 3.修改​​app/controller/home.js​

'use strict';

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

class HomeController extends Controller {

async index() {

const {
ctx,
} = this;

await ctx.render('index', ctx.query); // demoURL: http://127.0.0.1:7001/?name=Lee

}

}

module.exports = HomeController;

  • 4.建立页面​​app/view/index.html​

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<!-- .text{ color: red } -->
<link rel="stylesheet" href="/public/css/style.css">
</head>
<body>
<h1 class='text'>Hello <%= name %>!!!</h1>
</body>
</html>


举报

相关推荐

0 条评论