egg的基本使用

  一、脚手架(可以快速生成项目)

  1、新建一个项目文件夹,使用如下命令:

  2、npm  init  egg  --type=simple

  3、npm i 它会根据package.json里记录的所需包进行快速安装

  4、npm run dev 启动命令 :默认地址为http://localhost:7001

  二、编写Controller(控制器)

  
 // app/controller/home.js 项目建立完成后,会默认为你配置一个引导式的路由,你只需按着提示,逐步操作
const Controller = require('egg').Controller;
class HomeController extends Controller {
async index() {
this.ctx.body = 'Hello world';
}
   async list(){
     const {ctx} = this
     ctx.body='列表页'
   }
}
module.exports = HomeController;

//接着,在此app/router.js文件路径下配置路由,
module.exports = app => {
 const { router, controller } = app;
 //get请求 router.get(
'/', controller.home.index);
 router.get('/list',controller.home.list);
 //post请求需要在config/config.default.js配置,这里直接发起 POST 请求会报错:'secret is missing'。
 exports.security = {
  csrf:false
 } 
 router.post('/login',controller.home.login);
};



 
原文地址:https://www.cnblogs.com/LcxWeb/p/14110960.html