- 安裝koa npm i koa@2.0.0或者在packge.json文件 dependencies字段中加入 "koa":"2.0.0"字段,npm install 當(dāng)前工程nodes_modules目錄中會自動添加koa模塊
- 新建app.js
- 在app.js中添加如下代碼
<!--引入的koa模塊是個class,所以首字母需要大寫-->
const Koa =require('koa');
const app=new Koa();
app.use(async (ctx,next)=>{
console.log(`Process ${ctx.request.method} ${ctx.request.url} ....`);
<!--next()函數(shù)必須要有 會繼續(xù)執(zhí)行下一個use-->
await next();
});
app.use(async (ctx,next)=>{
const {path,body}=ctx.request;
if(path==='/test'){
body='Test page'
}else{
await next();
}
});
app.listen(3000);
console.log('app started at port 3000');
4.運(yùn)行 node app.js ,在控制臺上會顯示出app started at port 3000
上述代碼缺點(diǎn):新增鏈接都會再app.js文件中添加,導(dǎo)致后續(xù)代碼量越來越大荤牍,并且難以維護(hù)
- koa-router koa路由的作用是使url從代碼中分離出來码俩,單獨(dú)維護(hù)墨闲,不需要在異步函數(shù)中進(jìn)行判斷,安裝方式見1
<!--在上述代碼的基礎(chǔ)上添加-->
<!--(koa-router)返回的是函數(shù)-->
const router=require('koa-router')();
<!--改造app.use if(path==='/test')不需要在判斷-->
router.get('/test',async (ctx,next)=>{
......
});
- 上述只適用于get方式盟榴,post方式需要在安裝
koa-bodyparser
<!--在上述代碼的基礎(chǔ)上添加-->
<!--post請求-->
const bodyParser=require('koa=bodyparser');
<!--新增一個url-->
router.post('/signin',async (ctx,next)=>{
const {request,reponse}=ctx;
const {name,password}=request.body;
......
})
- 上述改造雖然使代碼結(jié)構(gòu)更加清晰磺芭,但是比沒有解決最開始的app.js代碼量過多的問題有梆。要解決app.js代碼量過多的問題是尖,需要如下操作:
新建controllers.js文件,負(fù)責(zé)遍歷在controller文件夾下的以.js結(jié)尾的文件泥耀,并且引入文件添加在router中
const fs = require('fs');
function addMapping(router, mapping) {
for (var url in mapping) {
if (url.startsWith('GET')) {
var path = url.substring(4);
router.get(path, mapping[url]);
console.log(`register url mapping:GET ${path}`);
} else if (url.startsWith('POST')) {
var path = url.substring(5);
router.post(path, mapping[url]);
console.log(`register URL mapping:POST ${path}`);
} else {
console.log(`invalid url:${url}`);
}
}
}
function addControllers(router) {
const files = fs.readdirSync(__dirname + '/controllers');
// 過濾出js文件
const js_files = files.filter(f => {
return f.endsWith('.js');
});
// 處理每個js文件
for (var f of js_files) {
console.log(`process controller:${f}`);
// 引入js文件
let mapping = require(__dirname + '/controllers/' + f);
addMapping(router, mapping);
}
}
module.exports = function(dir) {
let controllers_dir = dir || 'controllers',
router = require('koa-router')();
addControllers(router, controllers_dir);
return router.routes();
}
新建controller文件夾饺汹,js文件主要是異步處理函數(shù)
const fn_index=async (ctx,next)=>{
ctx.response.body = `<h1>Index</h1>
<form action='/signin' method='post'>
<p>Name:<input name='name' value='koa'/></p>
<p>Password:<input name='password' type='password'/></p>
<p><input type='submit' value='submit'/></p>
</form>`;
};
const fn_signin=async (ctx,next)=>{
const { request, response } = ctx;
const { name, password } = request.body;
console.log(`sigin with name:${name},password:${password}`);
if (name === 'koa' && password === '12345') {
response.body = `<h1>Welcome,${name}</h1>`;
} else {
response.body = `<h1>Login failed!</h1>
<p><a href='/'>Try again</a></p>`;
}
};
const fn_hello=async (ctx,next) =>{
const name=ctx.params.name;
ctx.response.body=`<h1>Hello,${name}!</h1>`;
}
module.exports={
'GET /':fn_index,
'POST /signin':fn_signin,
'GET /hello/:name':fn_hello
};
- 至此拆分結(jié)束 運(yùn)行node app.js
- git詳細(xì)代碼地址 https://github.com/jdkwky/webstudydeep/tree/webstudydeep/hello-koa
==參考:廖雪峰nodejs教程==