項目地址:https://github.com/caochangkui/demo/tree/koa-test
1. 創建項目
- 創建目錄 koa-test
- npm init 創建 package.json,然后執行 npm install
- 通過 npm install koa 安裝 koa 模塊
- 通過 npm install supervisor 安裝supervisor模塊, 用於node熱啟動
- 在根目錄下中新建 koa.js 文件,作為入口文件, 內容如下:
const Koa = require('koa'); // Koa 為一個class
const app = new Koa();
app.use(async (ctx, next) => {
await next();
ctx.response.body = 'Hello, koa2!';
});
app.listen(3333, () => {
console.log('This server is running at http://localhost:' + 3333)
})
- 配置 package.json 文件
{
"name": "koa-test",
"version": "1.0.0",
"description": "",
"main": "koa.js",
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1",
"serve": "supervisor koa.js"
},
"author": "",
"license": "ISC",
"dependencies": {
"koa": "^2.7.0",
"supervisor": "^0.12.0"
}
}
- 啟動項目, 打開 http://localhost:3333 即可
$ npm run serve
打開頁面后,顯示 hello koa2
2. 根據請求路徑顯示不同頁面
更改 koa.js
const Koa = require('koa'); // Koa 為一個class
const app = new Koa();
app.use(async (ctx, next) => {
await next();
if (ctx.request.path == '/about') {
ctx.response.type = 'html'; // 指定返回類型為 html 類型
ctx.response.body = 'this is about page <a href="/">Go Index Page</a>';
} else {
ctx.response.body = 'this is index page';
}
});
app.listen(3333, () => {
console.log('This server is running at http://localhost:' + 3333)
})
訪問:http://localhost:3333/about 顯示:this is about page Go Index Page
3. koa-router 路由管理模塊的使用
koa-router 是一個處理路由的中間件
$ npm i koa-router
修改koa.js
const Koa = require('koa'); // Koa 為一個class
const Router = require('koa-router') // koa 路由中間件
const app = new Koa();
const router = new Router(); // 實例化路由
// 添加url
router.get('/hello/:name', async (ctx, next) => {
var name = ctx.params.name; // 獲取請求參數
ctx.response.body = `<h5>Hello, ${name}!</h5>`;
});
router.get('/', async (ctx, next) => {
ctx.response.body = '<h5>Index</h5>';
});
app.use(router.routes());
app.listen(3333, () => {
console.log('This server is running at http://localhost:' + 3333)
})
也可給路由統一加個前綴:
const router = new Router({
prefix: '/api'
});
然后訪問 http://localhost:3333/api 即可,例如:http://localhost:3333/api/hello/koa2
4. post 請求
koa2 需要使用 koa-bodyparser 中間件來處理post請求
$ npm i koa-bodyparser
修改 koa.js
const Koa = require('koa'); // Koa 為一個class
const Router = require('koa-router') // koa 路由中間件
const bodyParser = require('koa-bodyparser'); // 處理post請求,把 koa2 上下文的表單數據解析到 ctx.request.body 中
const app = new Koa();
const router = new Router(); // 實例化路由
app.use(bodyParser())
// 表單
router.get('/', async (ctx, next) => {
ctx.response.body = `<h1>表單</h1>
<form action="/login" method="post">
<p>Name: <input name="name" value="koa2"></p>
<p>Password: <input name="password" type="password"></p>
<p><input type="submit" value="Submit"></p>
</form>`;
});
router.post('/login', async (ctx, next) => {
let name = ctx.request.body.name;
let password = ctx.request.body.password;
console.log(name, password);
ctx.response.body = `<h4>Hello, ${name}!</h4>`;
});
app.use(router.routes());
app.listen(3333, () => {
console.log('This server is running at http://localhost:' + 3333)
})
