koa 起步
程序员文章站
2024-03-25 09:31:04
...
创建 koa server
当前 koa 版本为 2.6.2
初始化项目:
mkdir koala
cd koala
npm init koala
npm install koa --save
创建 index.js,内容:
'use strict';
const koa = require('koa')
const app = new koa()
app.use(function *(){
this.body = "Hello World !!!";
});
app.listen(1234)
运行:
node index.js
浏览器访问 http://localhost:1234,会显示 "Hello World !!!"。
routing
安装:
npm install koa-router --save
修改 index.js
'use strict';
const koa = require('koa')
const koaRouter = require('koa-router')
const app = new koa()
const router = new koaRouter()
router.get('koala', '/', (ctx) => {
ctx.body = "Welcome! To the Koala Book of Everything!"
})
app.use(router.routes())
.use(router.allowedMethods())
app.listen(1234, () => console.log('running on port 1234'))
运行:
node index.js
浏览器访问 http://localhost:1234,会显示 "Welcome! koa routing!"。
错误处理
修改 index.js 添加错误处理代码:
app.use( async (ctx, next) => {
try {
await next()
} catch(err) {
console.log(err.status)
ctx.status = err.status || 500;
ctx.body = err.message;
}
})
修改 routing,抛出异常:
router.get('koala', '/', (ctx) => {
ctx.throw('Test Error Message', 500)
})
最终 index.js
'use strict';
const koa = require('koa')
const koaRouter = require('koa-router')
const app = new koa()
const router = new koaRouter()
app.use( async (ctx, next) => {
try {
await next()
} catch(err) {
console.log(err.status)
ctx.status = err.status || 500;
ctx.body = err.message;
}
})
router.get('koala', '/', (ctx) => {
// ctx.body = "Welcome! koa routing!"
ctx.throw('Test Error Message', 500)
})
app.use(router.routes())
.use(router.allowedMethods())
app.listen(1234, () => console.log('running on port 1234'))
重新运行 index.js,刷新页面,会显示:”Test Error Message“。
上一篇: vue起步