日韩性视频-久久久蜜桃-www中文字幕-在线中文字幕av-亚洲欧美一区二区三区四区-撸久久-香蕉视频一区-久久无码精品丰满人妻-国产高潮av-激情福利社-日韩av网址大全-国产精品久久999-日本五十路在线-性欧美在线-久久99精品波多结衣一区-男女午夜免费视频-黑人极品ⅴideos精品欧美棵-人人妻人人澡人人爽精品欧美一区-日韩一区在线看-欧美a级在线免费观看

歡迎訪問 生活随笔!

生活随笔

當前位置: 首頁 > 编程资源 > 编程问答 >内容正文

编程问答

koa2笔记

發布時間:2025/7/25 编程问答 28 豆豆
生活随笔 收集整理的這篇文章主要介紹了 koa2笔记 小編覺得挺不錯的,現在分享給大家,幫大家做個參考.

使用的時候

const app = new Koa2(); //application封裝各種方法,如use ,listen app.use(middleware) app.listen(1234) 復制代碼


application Context Request Response Middlewares Session Cookie復制代碼

中間鍵

... const mid1 = async(ctx,next)=>{ //async異步中間鍵 ctx.body= 'hello middleware' await next() //多個中間鍵,傳遞到下一個ctx.body = ctx.body + "233back function"//ctx.throw() //錯誤處理 也可try catch包裹處理錯誤//ctx.response.status = 404;//ctx.response.body = 'Page Not Found'; //錯誤處理 } ... app.use(mid1) app.listen(9527)復制代碼


koa-compose 中間鍵合成

const logger = (ctx, next) => {console.log(`${Date.now()} ${ctx.request.method} ${ctx.request.url}`);next(); }const main = ctx => {ctx.response.body = 'Hello World'; };const middlewares = compose([logger, main]); app.use(middlewares);復制代碼function compose (middleware) {return function (context, next) {// last called middleware #let index = -1return dispatch(0) //調用開始,指向dispathc(0)function dispatch (i) {if (i <= index) return Promise.reject(new Error('next() called multiple times'))index = iconst fn = middleware[i] || nextif (!fn) return Promise.resolve()try {return Promise.resolve(fn(context, function next () {return dispatch(i + 1) //循環調用,嵌套}))} catch (err) {return Promise.reject(err)}}}}復制代碼

koa-router ? ? ? ? ? ?路由

const about = ctx => {ctx.response.type = 'html';ctx.response.body = '<a href="/">Index Page</a>'; };const main = ctx => {ctx.response.body = 'Hello World';ctx.response.redirect('/'); //路由重定向 };app.use(route.get('/', main)); app.use(route.get('/about', about));復制代碼

裝飾器---實現路由模塊拆分

class Boy{@speak('what')run() {console.log('do something beore') } } function speak(dosomething){return function(target,key,descriptor){ //target被裝飾的類,key修飾的方法,descriptor詳細配置console.log(target)console.log(key)console.log(descriptor)target.dosomething= dosomethingreturn descriptor} } const mark = new Boy() mark.run()-------- @controller('/api/v0/movies') export class movieController{@get('/:id')@amin(['adminWebsit']) //檢查是否有管理員權限async getMovieDetail(ctx,next){...} }復制代碼

koa-static ? ? ? ? ? 靜態資源

const path = require('path'); const serve = require('koa-static');const main = serve(path.join(__dirname)); app.use(main);復制代碼

cookie ? ? ? ? ?****用法:服務端設置ctx.cookie

const main = function(ctx) {const n = Number(ctx.cookies.get('view') || 0) + 1; //改變數據ctx.cookies.set('view', n); //,數據變化ctx.response.body = n + ' views'; //每次展示cookie的時候}復制代碼

koa-body表單

const koaBody = require('koa-body');const main = async function(ctx) {const body = ctx.request.body;if (!body.name) ctx.throw(400, '.name required');ctx.body = { name: body.name }; };app.use(koaBody());執行: curl -X POST --data "name=Jack" 127.0.0.1:3000 上傳數據name=Jack到127.0.0::3000地址處 //顯示 {"name":"Jack"} 復制代碼

文件上傳

const os = require('os'); const path = require('path'); const koaBody = require('koa-body');const main = async function(ctx) {const tmpdir = os.tmpdir(); //拿到當前根目錄const filePaths = [];const files = ctx.request.body.files || {}; //拿到要上傳的文件for (let key in files) { //文件遍歷 const file = files[key];const filePath = path.join(tmpdir, file.name);const reader = fs.createReadStream(file.path);const writer = fs.createWriteStream(filePath);reader.pipe(writer); //文件遍歷 寫入filePaths.push(filePath); //輸出到filePath}ctx.body = filePaths; };app.use(koaBody({ multipart: true }));執行: $ curl --form upload=@/path/to/file http://127.0.0.1:3000 顯示: ["/tmp/file"]復制代碼

session

const Koa = require('koa') const logger = require('koa-logger') const session = require('koa-session') const app = new Koa()app.key= ['Hi Luke'] //app.use(logger()) app.use(session(app)) //這兒省略用了默認config,重要參數app.listen(2333)復制代碼


《新程序員》:云原生和全面數字化實踐50位技術專家共同創作,文字、視頻、音頻交互閱讀

總結

以上是生活随笔為你收集整理的koa2笔记的全部內容,希望文章能夠幫你解決所遇到的問題。

如果覺得生活随笔網站內容還不錯,歡迎將生活随笔推薦給好友。