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')
})

 

效果預覽

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM