koa2入門(2) koa-router 路由處理


項目地址:https://github.com/caochangkui/demo/tree/koa-test

1. 創建項目

  1. 創建目錄 koa-test
  2. npm init 創建 package.json,然后執行 npm install
  3. 通過 npm install koa 安裝 koa 模塊
  4. 通過 npm install supervisor 安裝supervisor模塊, 用於node熱啟動
  5. 在根目錄下中新建 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)
})
  1. 配置 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"
  }
}

  1. 啟動項目, 打開 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)
})

參考: https://www.liaoxuefeng.com/wiki/001434446689867b27157e896e74d51a89c25cc8b43bdb3000/001471087582981d6c0ea265bf241b59a04fa6f61d767f6000


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM