裸上Koa
cd ~/Workspace
mkdir helloworld
cd helloworld
yarn init
yarn add koa
vi package.json
在package.json
里增加scripts
,我用了nodemon
需要提前通过yarn add -g nodemon
安装。
{
"name": "bluepool-backend",
"version": "1.0.0",
"description": "The bluepool backend",
"main": "index.js",
"author": "W.H.",
"license": "MIT",
"scripts": {
"dev-build": "nodemon build",
"build": "node build",
"dev": "nodemon run",
"run": "node run"
},
"dependencies": {
"koa": "^2.13.1"
}
}
在helloworld
目录创建index.js
文件。讲[https://koajs.com/]的样例代码copy进去,保存。
const Koa = require('koa');
const app = new Koa();
app.use(async ctx => {
ctx.body = 'Hello World';
});
app.listen(3000);
在Terminal
里执行
yarn dev
浏览器输入http://localhost:3000
可以看到Hello World了。
2
安装koa-router
,更多参考https://github.com/koajs/router。
yarn add @koa/router
修改index.js
const Koa = require('koa');
const Router = require('@koa/router');
const app = new Koa();
const router = new Router();
router.get('/', (ctx, next) => {
// ctx.router available
ctx.body = { 'hello': 'world' }
});
app
.use(router.routes())
.use(router.allowedMethods());
app.listen(3000);
浏览器页面刷新可以看到{"hello", "world"}
了。