標籤: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