egg 简单demo学习

egg 简单demo学习_第1张图片

添加模版引擎

npm i egg-view-ejs --save

2.找到 {app_root}/config/plugin.js

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

3.找到 {app_root}/config/config.default.js

配置:

'use strict';

module.exports = appInfo => {
  const config = exports = {};

  // use for cookie sign key, should change to your own and keep security
  config.keys = appInfo.name + '_1532656413112_8161';

  // add your config here
  config.middleware = [];

  //配置ejs模板引擎
  config.view = {
    mapping: {
      '.html': 'ejs',
    }
  };


  //配置公共的api

  config.api='http://www.xxx.com/';

  return config;
};

 

新闻控制器

'use strict';

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

class NewsController extends Controller {
  async index() {
    


    //获取数据显示到新闻页面

    var list=await this.service.news.getNewsList();


    await this.ctx.render('news',{

      list:list
    })
  } 
  async content(){


    //获取get传值

    var aid=this.ctx.query.aid;

    console.log(aid);


    var list=await this.service.news.getNewsContent(aid);

    console.log(list);

    await this.ctx.render('newscontent',{

      list:list[0]
    })



  }
}

module.exports = NewsController;

新闻服务:

'use strict';

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

class NewsService extends Service {
  async getNewsList() {
    
    //通过抓取接口返回数据

    // curl的方法可以获取远程的数据


    var api=this.config.api+'appapi.php?a=getPortalList&catid=20&page=1'


    var response=await this.ctx.curl(api);

    // console.log(response.data); // 返回的是Buffer

    var data=JSON.parse(response.data);    //把Buffer类型转转换成对象

    // console.log(data);
    return data.result;

  }

  //获取新闻详情

  async getNewsContent(aid){


    var api=this.config.api+'appapi.php?a=getPortalArticle&aid='+aid;


    var response=await this.ctx.curl(api);

    var data=JSON.parse(response.data);    //把Buffer类型转转换成对象

    return data.result;

  }
}

module.exports = NewsService;

新闻view显示:




    
    
    
    Document


    
    

新闻列表数据

新闻详情显示:




    
    
    
    Document

    


  

    

<%=list.title%>

<%-list.content%>

路由配置

router.js

'use strict';

/**
 * @param {Egg.Application} app - egg application
 */
module.exports = app => {
  const { router, controller } = app;
  router.get('/', controller.home.index);

  router.get('/news', controller.news.index);

  router.get('/newscontent', controller.news.content);
};

 

你可能感兴趣的:(egg 简单demo学习)