1- 安装模块

  1. yarn add koa koa-router koa2-cors
  2. cnpm i nodemon -g

models/top250.js

  1. //models/top250.js
  2. const mongoose = require("mongoose");
  3. /* 1.连接本地数据库 */
  4. mongoose.connect( 'mongodb://127.0.0.1:27017/movies', {useNewUrlParser: true});
  5. /* 2.在本地定义一个Schema和远程的数据库的字段映射 */
  6. var Top250Schema = new mongoose.Schema({
  7. name:String,
  8. rating:Number
  9. });
  10. /* 3.创建数据模型,和数据库中的表映射,获取表 */
  11. /* Top250Model 是我们获取的top250那张表 */
  12. var Top250Model = mongoose.model("top250",Top250Schema,"top250")
  13. module.exports = Top250Model;

index.js

  1. //index.js
  2. const koa = require("koa");
  3. const router = require("koa-router")();
  4. const Top250Model = require("./models/top250");
  5. const cors = require("koa2-cors");
  6. const app = new koa();
  7. /* top250路由去读取数据库中的数据 */
  8. router.get("/top250",async ctx=>{
  9. var data = await Top250Model.find({})
  10. ctx.body = {
  11. data,
  12. code:200
  13. }
  14. })
  15. app.use(cors());
  16. app.use(router.routes());
  17. app.listen(8080)