- 安装koa2环境
1)初始化:npm init
2)在npm官网:npmjs.com中搜索koa,并找到安装命令:npm i koa
3)执行命令 npm i koa --save
安装完成,版本为2.13.4
- 引入koa,代码如下:
const Koa = require('koa') // commonjs模块化
const app = new Koa();
// ctx context 上下文
app.use(async (ctx ) => {
ctx.body = 'hello world';
})
app.listen(3000); // web server 监听3000端口
- 与nodejs代码比较:
// nodejs 对比
const http = require('http')
const server = http.createServer((req, res) => {
const url = req.url;
const path = url.split('?')[0];
res.end(path+'1234')
});
server.listen(3000)