1-1 加载页面

在controller 文件夹 新建 home.js

  1. 'use strict';
  2. const Controller = require('egg').Controller;
  3. class HomeController extends Controller {
  4. async index() {
  5. const { ctx } = this;
  6. var db = this.app.mongodb;
  7. const collection = await db.collection('member');
  8. //拿到member中所有数据
  9. var members = await collection.find().toArray();
  10. console.log(members);
  11. await ctx.render("/home",{members});
  12. }
  13. }
  14. module.exports = HomeController;

在view 文件夹 新建 home.html

  1. <!DOCTYPE html>
  2. <html lang="en">
  3. <head>
  4. <meta charset="UTF-8">
  5. <meta http-equiv="X-UA-Compatible" content="IE=edge">
  6. <meta name="viewport" content="width=device-width, initial-scale=1.0">
  7. <title>Document</title>
  8. <style>
  9. .logo {
  10. width: 50px;
  11. }
  12. </style>
  13. <meta name="referrer" content="no-referrer" />
  14. <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/3.4.1/css/bootstrap.min.css">
  15. </head>
  16. <body>
  17. <div class="container">
  18. <table class="table table-hover">
  19. <thead>
  20. <tr>
  21. <th>id</th>
  22. <th>姓名</th>
  23. <th>年龄</th>
  24. <th>性别</th>
  25. <th>头像</th>
  26. <th>删除</th>
  27. </tr>
  28. </thead>
  29. <tbody>
  30. {%for item in members%}
  31. <tr>
  32. <td>{{item._id}}</td>
  33. <td><a href="/detail?_id={{item._id}}">{{item.username}}</a></td>
  34. <td>{{item.age}}</td>
  35. <td>{{item.sex}}</td>
  36. <td><img class="logo" src="{{item.logo}}" alt=""></td>
  37. <td><a href="/doDelete?_id={{item._id}}" class="btn btn-danger">删除</a></td>
  38. </tr>
  39. {% endfor %}
  40. </tbody>
  41. </table>
  42. </div>
  43. </body>
  44. </html>

对应路由

  1. router.get('/form', controller.form.index);