Koa(二、post傳值,art-template模板,靜態(tài)資源中間件)

post數(shù)據(jù)

  • 原生node.js實(shí)現(xiàn)post請求數(shù)據(jù)獲取
common.js:
//獲取post請求提交的數(shù)據(jù)
function getPostInfo(ctx){
    //獲取數(shù)據(jù),異步
    return new Promise((resolve,reject)=>{
        let postInfo='';
        try {
            ctx.req.on("data",shunk=>{
                postInfo+=shunk;
            })
            ctx.req.on("end",()=>{
                resolve(postInfo);
            })
        } catch (error) {
            reject(error)
        }
    })
}
module.exports={getPostInfo}

index.js:
引入=》
common=requie('./module/common.js')
querystring = requir('querystring')

解析和調(diào)用:
let info= await common.getPostInfo(ctx);
let obj=querystring.parse(info);
console.log(info);//username=asfa&password=assafa
console.log(obj)//{ username: 'asa', password: 'asca' }

bodyParse解析

  • cnpm i koa-bodyparser --save
  • bodyParser=require('koa-bodyparser')
  • app.use(bodyParser()):注意內(nèi)部是方法
router.post('/doAdd',async(ctx)=>{
    ctx.body=ctx.request.body;
    //{"username":"asda","password":"asfa"}
})
說明:koa-bodyparser是ctx.request而不是原生的ctx.req

koa-static靜態(tài)資源中間件

  • cnpm i koa-static --save
  • static=require('koa-static')
  • app.use(static('static'));
  • 靜態(tài)資源中間件可以配置多個(gè),靜態(tài)資源時(shí)候會(huì)依次查找每個(gè)中間的路徑
例如:引入css
<link rel="stylesheet" href="css/a.css">
此時(shí)的路徑和index.ejs路徑?jīng)]關(guān)系,直接會(huì)去static目錄下查找。

art-template模板

說明:art-template如果和koa搭配使用需要安裝 koa-art-template

  • cnpm i art-template
  • cnpm i koa-art-template

連接地址:https://www.npmjs.com/package/koa-art-template

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請結(jié)合常識與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡書系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容