Koa快速入门
1.新建项目
通过命令创建项目:
mkdir koa-quick-start
cd koa-quick-start
npm init -yes
可以看到koa-quick-start
下面有package.json
{
"name": "koa-quick-start",
"version": "1.0.0",
"description": "",
"main": "index.js",
"scripts": {
"test": "echo "Error: no test specified" && exit 1"
},
"keywords": [],
"author": "",
"license": "ISC"
}
2.下载koa包
npm install koa
记得观察一下package.json
{
"name": "koa-quick-start",
"version": "1.0.0",
"description": "",
"main": "index.js",
"scripts": {
"test": "echo "Error: no test specified" && exit 1"
},
"keywords": [],
"author": "",
"license": "ISC",
"dependencies": {
"koa": "^2.11.0"
}
}
没错,多了koa
的依赖
并且还在项目中多了node_modules
文件夹
3.Hello World
是时候写Hello World
新建文件index.js
键入如下代码:
代码语言:javascript复制const Koa =require('koa');
const app=new Koa();
app.use(async (ctx, next) => {
await next()
ctx.response.type = 'text/html'
ctx.response.body = '<h1>Hello World</h1>'
});
console.log("koa start,listen 3000...");
app.listen(3000);
运行起来
代码语言:javascript复制node index.js
koa start,listen 3000...