1. 程式人生 > >Koa2學習系列04-POST/GET請求——常見請求方式處理

Koa2學習系列04-POST/GET請求——常見請求方式處理

Http 請求

在學習了 koa-router 之後,我們就可以用它來處理一些常見的請求了,比如 POST/GET 。

 

koa-router 提供了 .get.post.put 和 .del 介面來處理各種請求,但實際業務上,我們大部分只會接觸到 POST 和 GET,所以接下來只針對這兩種請求型別來說明。

 

當我們捕獲到請求後,一般都需要把請求帶過來的資料解析出來。資料傳遞過來的方式一般有三種:

 

請求引數放在 URL 後面

http://localhost:3000/home?id=12&name=ikcamp

 

koa-router 封裝的 request 物件,裡面的 query 方法或 querystring 方法可以直接獲取到 Get 請求的資料,唯一不同的是 query 返回的是物件,而 querystring 返回的是字串。

修改 app.js,我們加入解析方式:

  const Koa = require('koa')
  const router = require('koa-router')()
  const app = new Koa()

  router.get('/', async(ctx, next) => {
    ctx.response.body = `<h1>index page</h1>`
  })

  router.get('/home', async(ctx, next) => {
    console.log(ctx.request.query)
    console.log(ctx.request.querystring)
    ctx.response.body = '<h1>HOME page</h1>'
  })

  router.get('/404', async(ctx, next) => {
    ctx.response.body = '<h1>404 Not Found</h1>'
  })

  // add router middleware:
  app.use(router.routes())

  app.listen(3000, () => {
    console.log('server is running at http://localhost:3000')
  })

 

執行程式碼,並通過瀏覽器訪問 http://localhost:3000/home?id=12&name=ikcamp,然後開啟控制檯會看到下面的輸出內容:

{ id: '12', name: 'ikcamp' }
id=12&name=ikcamp

 

請求引數放在 URL 中間

http://localhost:3000/home/12/ikcamp

 

這種情況下,解析方式肯定與上面的不一樣了,koa-router 會把請求引數解析在 params 物件上,我們修改 app.js

 檔案,增加新的路由來測試下:

  // 增加如下程式碼
  router.get('/home/:id/:name', async(ctx, next)=>{
    console.log(ctx.params)
    ctx.response.body = '<h1>HOME page /:id/:name</h1>'
  })

 

執行程式碼,並通過瀏覽器訪問 http://localhost:3000/home/12/ikcamp,然後檢視下控制檯顯示的日誌資訊:

{ id: '12', name: 'ikcamp' } 

 

請求引數放在 body 中

 

當用 post 方式請求時,我們會遇到一個問題:post 請求通常都會通過表單或 JSON 形式傳送,而無論是 Node 還是 Koa,都 沒有提供 解析 post 請求引數的功能。

 

koa-bodyparser 說:『是時候登場了!』

 

首先,安裝 koa-bodyparser 包:

npm i koa-bodyparser -S

 

安裝完成之後,我們需要在 app.js 中引入中介軟體並應用:

  const Koa = require('koa')
  const router = require('koa-router')()
  const bodyParser = require('koa-bodyparser')
  const app = new Koa()

  app.use(bodyParser())

  router.get('/', async(ctx, next) => {
    ctx.response.body = `<h1>index page</h1>`
  })

  router.get('/home', async(ctx, next) => {
    console.log(ctx.request.query)
    console.log(ctx.request.querystring)
    ctx.response.body = '<h1>HOME page</h1>'
  })

  router.get('/home/:id/:name', async(ctx, next)=>{
    console.log(ctx.params)
    ctx.response.body = '<h1>HOME page /:id/:name</h1>'
  })

  router.get('/404', async(ctx, next) => {
    ctx.response.body = '<h1>404 Not Found</h1>'
  })

  app.use(router.routes())

  app.listen(3000, () => {
    console.log('server is running at http://localhost:3000')
  })

然後我們來試著寫一個簡單的表單提交例項。修改 app.js 增加如下程式碼,實現增加表單頁面的路由:

  // 增加返回表單頁面的路由
  router.get('/user', async(ctx, next)=>{
    ctx.response.body = 
    `
      <form action="/user/register" method="post">
        <input name="name" type="text" placeholder="請輸入使用者名稱:ikcamp"/> 
        <br/>
        <input name="password" type="text" placeholder="請輸入密碼:123456"/>
        <br/> 
        <button>GoGoGo</button>
      </form>
    `
  })

 

繼續修改 app.js 增加如下程式碼,實現 post 表單提交對應的路由:

  // 增加響應表單請求的路由
  router.post('/user/register',async(ctx, next)=>{
    let {name, password} = ctx.request.body
    if( name === 'ikcamp' && password === '123456' ){
      ctx.response.body = `Hello, ${name}!`
    }else{
      ctx.response.body = '賬號資訊錯誤'
    }
  })

 

常見的幾種請求,以及相應的引數傳遞解析,我們已經學習過了。下一節中,我們會把專案整理重構下,做個分層,並引入檢視層。

原文https://github.com/ikcamp/koa2-tutorial/tree/3-router-request