zoukankan      html  css  js  c++  java
  • koa2链接mongodb

    数据库使用的mongodb
    mongodb下载:https://www.mongodb.com/
    mongodb GUI:https://robomongo.org/

    使用中间件koa来搭建框架
    使用中间件monk来链接数据库

    // 导入koa,和koa 1.x不同,在koa2中,我们导入的是一个class,因此用大写的Koa表示:
    const Koa = require('koa');
    const Router = require('koa-router');
    const Monk = require('monk');
    // 创建一个Koa对象表示web app本身:
    const app = new Koa();
    const router=new Router();
    const db=new Monk('localhost/School');//链接到库
    const students = db.get('student');//
    
    
    // 打印request URL:
    app.use(async (ctx, next) => {
        console.log(`Process ${ctx.request.method} ${ctx.request.url}...`);
        await next();
    });
    
    
    // 对于任何请求,app将调用该异步函数处理请求:
    router.get('/', async ( ctx ) => {
      ctx.response.type = 'text/html';
      ctx.body = 'hi'
    })
    router.get('/getList', async ( ctx ) => {
      let st = await students.find();
      ctx.response.type = 'application/json';
      ctx.body = st;
    })
    
    
    // 加载路由中间件
    //解释:app.use 加载用于处理http請求的middleware(中间件),当一个请求来的时候,会依次被这些 middlewares处理。
    app.use(router.routes());
    
    // 在端口3000监听:
    app.listen(3000, () => {
      console.log('[myapp]已经运行,端口为300')
    })

    效果预览

  • 相关阅读:
    Orleans介绍
    Orleans入门
    mongodb for windows安装
    ASP.NET Identity
    OWIN与Katana
    手动搭建ABP2.1.3 Zero——基础框架
    ABP学习笔记
    ABP-Zero模块
    ABP单元测试
    ABP-JavaScript API
  • 原文地址:https://www.cnblogs.com/dshvv/p/7693418.html
Copyright © 2011-2022 走看看