运行环境 node v12.15.0
安装 egg
mkdir egg-example && cd egg-example npm init egg --type=simple npm i启动
npm run dev open http://localhost:7001因为 egg 是在 koa 框架上面的二次封装,所以默认大家在阅读这篇文章之前,就已经懂得了 koa,这样里面的一些基本知识我们就不做特别仔细的说明了。其实熟悉 koa 框架的开发者看 egg,就笔者自身而言,这两个框架的编写确实差不多。
原来的 router.js 文件
router.get('/product', controller.product.index)在 controller 文件夹里面新建一个 product.js
const Controller = require('egg').Controller class ProductController extends Controller { async index() { const { ctx } = this; const res = await ctx.service.product.index() ctx.body = res } } module.exports = ProductController;controller 文件夹同级目录下,新建一个 service 文件夹,新建一个 product.js(模仿数据返回的数据,这一层就是用来直接操作数据库的)
const Service = require('egg').Service class ProductService extends Service { async index() { return { id: 100, name: '测试' } } } module.exports = ProductService在 config / config.default.js 修改如下配置
/* eslint valid-jsdoc: "off" */ 'use strict'; /** * @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 + '_1601779739658_666'; // add your middleware config here config.middleware = []; // csrf 设置为 false config.security = { csrf: { enable: false } } // 可先注释,后面讲到 ejs 的时候,把注释去掉 config.view = { mapping: { '.html': 'ejs', }, }; // add your user config here const userConfig = { // myAppName: 'egg', }; return { ...config, ...userConfig, }; };访问 localhost:7001/product 出现相对应的数据,代表接口成功实现
我们继续编写
请求地址里面携带参数的,有两种情况,一种是以 ? 的形式加在进行拼接的,一种是以 / 直接加在后面的
router.get('/product/detail', controller.product.detail) router.get('/product/detail2/:id', controller.product.detail2) async detail() { const { ctx } = this console.log(ctx.query) ctx.body = `id = ${ctx.query.id}`; } async detail2() { const { ctx } = this; console.log(ctx.params) ctx.body = `id2 = ${ctx.params.id}` }说完 get 请求之后,我们来说 post 请求
router.post('/product/create', controller.product.create) async create() { const { ctx } = this; console.log(ctx.request.body) const { color } = ctx.request.body ctx.body = { color } }温馨提示:这个要用 postman 测试,测试的时候
不然,console.log 输出的就是一个 {}
修改信息 put
router.put('/product/update/:id', controller.product.update) async update() { const { ctx } = this; console.log(ctx.params) ctx.body = { id: ctx.params.id } }删除
router.delete('/product/delete/:id', controller.product.delete) async delete() { const { ctx } = this; console.log(ctx.params) // const { color } = ctx.request.body ctx.body = { id: 123 } }大概就是这个样子了。是不是很 koa 差不多呢,很熟悉 有木有😀😀😀
模板渲染 ejs 来了。 安装
npm install egg-view-ejs --saveapp 文件夹下,新建 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>index</title> <link rel="stylesheet" href="/public/css/main.css"> </head> <body> <h1>this is index page</h1> <p> <%=res.id%> </p> <p> <%=res.name%> </p> <img src="/public/img/14.jpg" alt=""> <ul> <%for(var i = 0; i <lists.length; i++){%> <li><%=lists[i]%></li> <%}%> </ul> <script src="/public/js/main.js"></script> </body> </html>(不认识没有关系)😂😂😂😂 (public 下 新建相对应的文件夹,里面新建相对应的文件,随便写点什么东西,测试一下)
config / plugin.js
// {app_root}/config/plugin.js exports.ejs = { enable: true, package: 'egg-view-ejs', };修改 controller 下的 home.js,查看效果
'use strict'; const Controller = require('egg').Controller; class HomeController extends Controller { async index() { const { ctx } = this; const res = await ctx.service.product.index() await ctx.render('index.html', { res, lists: ['a', 'b', 'c'] }) } } module.exports = HomeController;入门就到这里了。是不是很简单,有木有👏👏👏👏👏👏👏