koa_router的使用
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24
|
const Koa = require('koa'); const router = require('koa-router')();
const app = new Koa();
app.use(async ctx => { ctx.body = 'Hello World'; });
router.get("/", async(ctx) => { ctx.body = "首页"; })
app.use(router.routes()); app.use(router.allwedMethods());
app.listen(3000, () => { console.log('应用已经启动,http://localhost:3000'); });
|
获取grt传值
1 2 3 4 5 6 7 8 9 10 11 12 13
| router.get("/new", async(ctx) => { console.log(ctx.url); console.log(ctx.query); console.log(ctx.response.query); })
|
动态路由
1 2 3 4
| router.get("/new/:id", async(ctx) => { console.log(ctx.params); })
|
动态路由也可以传多个值,例如/new/:id/:did
然后会收到{id: ?, did: ?}
接收post请求的数据
可以用原生node.js来接收,先封装成promise,之后await接收结果。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18
| exports.parsePostData = function(ctx) { return new Promise((resolve, reject) => { try{ let postdata=""; ctx.req.on('data', (data) => { postdata += data }) ctx.req.on('end', () => { resolve(postdata); }) }catch(error) { reject(error); } }) }
|
也可以方便一些用koa-bodyparser这个中间件接收。
1 2 3 4 5 6 7 8 9 10
|
const bodyParser = require('boa-bodyparser');
app.use(bodyParser());
router.post("/new", (ctx) => { console.log(ctx.request.body) })
|
koa封装mongodb的工具
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16
| const DB=require('./module/db.js');
router.get('/',async (ctx)=>{
console.time('start'); var result=await DB.find('user',{});
console.timeEnd('start'); console.log(result); await ctx.render('index',{ list:{ name:'张三' } }); })
|
1 2 3 4 5 6 7 8 9 10 11
|
const app={
dbUrl: 'mongodb://localhost:27017/',
dbName: 'koa'
}
module.exports=app;
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81
| const MongoClient = require('mongodb').MongoClient;
const Config=require('./config.js');
class Db{
static getInstance(){
if(!Db.instance){ Db.instance=new Db(); } return Db.instance; }
constructor(){
this.dbClient=''; this.connect();
}
connect(){ let _that=this; return new Promise((resolve,reject)=>{ if(!_that.dbClient){ MongoClient.connect(Config.dbUrl,(err,client)=>{
if(err){ reject(err)
}else{
_that.dbClient=client.db(Config.dbName); resolve(_that.dbClient) } })
}else{ resolve(_that.dbClient);
}
})
}
find(collectionName,json){
return new Promise((resolve,reject)=>{
this.connect().then((db)=>{
var result=db.collection(collectionName).find(json);
result.toArray(function(err,docs){
if(err){ reject(err); return; } resolve(docs); })
}) }) } update(){
} insert(){
} }
module.exports=Db.getInstance();
|