koa2連結mongodb

來源:互聯網
上載者:User

標籤:ges   資料   image   搭建   連接埠   async   nts   http   request   

資料庫使用的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‘)})

 

效果預覽

 

koa2連結mongodb

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.