koa2連接mongodb

數據庫使用的mongodb
mongodb下載:https://www.mongodb.com/
mongodb GUI:https://robomongo.org/
html

 

使用中間件koa來搭建框架
使用中間件monk來連接數據庫web

// 導入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')
})

 

效果預覽
mongodb

相關文章
相關標籤/搜索