其實腳手架生成的初始項目目錄 app/controller/home.js 已是個簡單的例子前端
如今,先在controller下新建一個js文件-> news.jsapp
引入控制器,新建類,導出類異步
const Controller = require('egg').Controller; class NewsController extends Controller{ //類名大寫 async list(){ // async await 異步 const dataList = await this.data(); this.ctx.body = { code:0, masg:'success!', data:dataList }; } async data(){ return { list:[ { id: 1, title: 'news1', url: 'https://i.loli.net/2019/05/20/5ce26578e0e5549312.png' }, { id: 2, title: 'news2', url: 'https://i.loli.net/2019/05/20/5ce2657a0e01277224.png' }, { id: 3, title: 'news3', url: 'https://i.loli.net/2019/05/20/5ce2657b67be250185.png' }, ] } } } module.exports = NewsController; //別忘了導出類
以後,打開app/router.js 新建一個接口 router.get('/list', controller.news.list);
注意路徑不要寫錯async
module.exports = app => { const { router, controller } = app; router.get('/', controller.home.index); router.get('/list', controller.news.list); };
完成以後就能夠打開咱們的前端項目進行接口請求,能夠看到返回的內容。成功~ui