1. 簡單處理http
中介軟體處理請求
// router.js
async
function
handlereq
(ctx, next)
module.exports =
;
詳細request內包含的屬性可檢視: koa2 context.request
2. get請求
3. post請求
// queryrequest.js
// 手動獲取post資料
const
parsepostdata
= ctx =>
newpromise
((resolve, reject)
=>);
// 以end為querystring結束的標誌
ctx.req.
addlistener
('end',(
)=>);
});// 載入表單模板(為了測試post請求結果)
4. bodyparser處理post請求
1. 安裝koa-bodyparser
yarn add koa-bodyparser
2. 匯入koa-bodyparser中介軟體const bodyparser =
require
('koa-bodyparser');
use(
bodyparser()
);// 這裡新增了koa-router
apirouter.
get(
'/body'
,async ctx =>);
// use koa-bodyparser
apirouter.
post
('/body/postname'
,async ctx =>
);
notes: 如果新增了koa-bodyparser之前通過監控ctx.req中的data和end的事件的獲取post引數的方法可能失效
koa2 設計模式-學習筆記
koa 官網
koa2 高階學習筆記
處理HTTP請求
處理http請求 當客戶端瀏覽器通過url訪問web應用時,首先要做的就是獲取使用者提交的資訊,也就是從http請求資料中獲得的資訊。http請求資料分為http請求頭和body http請求頭包含了一些http請求欄位和http get欄位 body中可以包含任何型別的資料,包含http get欄...
koa學習筆記
const koa require koa 複製 context物件表示一次會話的上下文,包含response和request.可以控制返回給使用者的內容,例如 const koa require koa const main ctx 複製 koa預設返回的是text plain。如果想要返回其他型...
koa 學習筆記
同當前炙手可熱的express一樣,它是一款更年輕的web應用框架 koa,是 express 原班人馬基於 es6 新特性重新開發的框架,主要基於co 中介軟體,框架自身不包含任何中介軟體,很多功能需要借助第三方中介軟體解決,但是由於其基於 es6 generator 特性的非同步流程控制,解決了...