eggjs实战从0开始(2)-第一个demo

76 阅读1分钟

1.app文件夹

写一个最简单的demo,其他文件可以先不用关注,官网有每个文件夹详细介绍。
和业务相关的代码,主要在app文件夹中。
在这里插入图片描述
news.js就是我仿照home中的代码写的一个小demo,亲测有效。

2.代码分析

news.js文件中所有代码如下:

'use strict';  //js代码严格模式,可写可不写,写上主要是为了规范自己代码中的变量声明。

/*egg框架肯定是将controller这些类都写到了一个叫egg.js的文件中。
*可以用官网的方式调用controller,也可以解构的方式调用。
*对我而言,既然上手node,所以尽量多适应这种新语法。*/
const {Controller} = require('egg');  

//写一个自己的控制器NewsController,controller中写业务代码                                                     
class NewsController extends Controller {
//写一个自己的接口list
    async list(){
    //用解构的方式得到上下文对象,上下文中又包含请求request和响应response两个对象
        const {ctx} = this; 
        //响应对象可以省略不写,下面语法等同于 ctx.response.body='this is news list'
        ctx.body='this is news list'
    }

}
//导出自己的控制器,固定写法。
module.exports = NewsController;