<ruby id="bdb3f"></ruby>

    <p id="bdb3f"><cite id="bdb3f"></cite></p>

      <p id="bdb3f"><cite id="bdb3f"><th id="bdb3f"></th></cite></p><p id="bdb3f"></p>
        <p id="bdb3f"><cite id="bdb3f"></cite></p>

          <pre id="bdb3f"></pre>
          <pre id="bdb3f"><del id="bdb3f"><thead id="bdb3f"></thead></del></pre>

          <ruby id="bdb3f"><mark id="bdb3f"></mark></ruby><ruby id="bdb3f"></ruby>
          <pre id="bdb3f"><pre id="bdb3f"><mark id="bdb3f"></mark></pre></pre><output id="bdb3f"></output><p id="bdb3f"></p><p id="bdb3f"></p>

          <pre id="bdb3f"><del id="bdb3f"><progress id="bdb3f"></progress></del></pre>

                <ruby id="bdb3f"></ruby>

                企業??AI智能體構建引擎,智能編排和調試,一鍵部署,支持知識庫和私有化部署方案 廣告
                [TOC] 隨著ES6的普及,async/await的語法受到更多JS開發者的青睞,Koa.js作為比較早支持使用該語法的Node框架越來越受到大家的喜愛,雖然Koa.js本身支持的功能很有限,但官方和社區提供了很多各種功能的中間件,精選了我們開發應用程序或者框架將會特別有用的中間件。 Koa.js 插件可以到[https://github.com/koajs/koa/wiki](https://github.com/koajs/koa/wiki)獲取。 # [koa-router](https://github.com/ZijianHe/koa-router) 路由是Web框架必不可少的基礎功能,koa.js為了保持自身的精簡,并沒有像Express.js自帶了路由功能,因此koa-router做了很好的補充,作為koa星數最多的中間件,koa-router提供了全面的路由功能,比如類似Express的app.get/post/put的寫法,URL命名參數、路由命名、支持加載多個中間件、嵌套路由等。 Basic usage: ~~~js var Koa = require('koa'); var Router = require('koa-router'); var app = new Koa(); var router = new Router(); router.get('/', (ctx, next) => { // ctx.router available }); app .use(router.routes()) .use(router.allowedMethods()); ~~~ # [koa-bodyparser](https://github.com/koajs/bodyparser) koa.js并沒有內置Request Body的解析器,當我們需要解析請求體時需要加載額外的中間件,官方提供的koa-bodyparser是個很不錯的選擇,支持x-www-form-urlencoded, application/json等格式的請求體,但不支持form-data的請求體。 ## Usage ~~~js var Koa = require('koa'); var bodyParser = require('koa-bodyparser'); var app = new Koa(); app.use(bodyParser()); app.use(async ctx => { // the parsed body will store in ctx.request.body // if nothing was parsed, body will be an empty object {} ctx.body = ctx.request.body; }); ~~~ # [koa-multer](https://github.com/koa-modules/multer) ~~~jvascripta const Koa = require('koa') const multer = require('koa-multer') const Router = require('koa-router') const app = new Koa(); const router = new Router(); const upload = multer({ dest: 'uploads/' }); //路由 router.post('/upload', upload.single('file'), async (ctx, next) => { ctx.body = { filename: ctx.req.file.filename//返回文件名 } }) app.use(router.routes()).use(router.allowedMethods()) app.listen(3000); ~~~ 也可以配置storage ```javascript //文件上傳 //配置 const storage = multer.diskStorage({ //文件保存路徑 destination: function (req, file, cb) { cb(null, 'public/uploads/') }, //修改文件名稱 filename: function (req, file, cb) { var fileFormat = (file.originalname).split("."); //以點分割成數組,數組的最后一項就是后綴名 cb(null, Date.now() + "." + fileFormat[fileFormat.length - 1]); } }) //加載配置 const upload = multer({ storage: storage }); ``` # [koa-views](https://github.com/queckezz/koa-views) koa-views對需要進行視圖模板渲染的應用是個不可缺少的中間件,支持ejs, nunjucks等眾多模板引擎。 ## Example ~~~js const Koa = require('koa') const Router = require('koa-router') const views = require('koa-views') const compose = require('koa-compose') const path = require('path') const app = new Koa() // Must be used before any router is used app.use(views(path.join(__dirname, 'views'), { map: { html: 'nunjucks' } //需要安裝nunjucks包 })) const router = new Router() router.get('/', async (ctx, next) => { await ctx.render('multer', { title: 'Hello koa2' }) }) //組合多個中間件,中間件執行區分順序 const all = compose([router.routes(), router.allowedMethods()]); app.use(all); app.listen(3000, () => { console.log('server is running at http://localhost:3000') }); ~~~ # [koa-static](https://github.com/koajs/static) Node.js除了處理動態請求,也可以用作類似Nginx的靜態文件服務,在本地開發時特別方便,可用于加載前端文件或后端Fake數據。 ~~~js const Koa = require('koa'); const app = new Koa(); app.use(require('koa-static')(root, opts)); ~~~ * `root`root directory string. nothing above this root directory can be served * `opts`options object. ## Example ~~~js const serve = require('koa-static'); const Koa = require('koa'); const app = new Koa(); // $ GET /package.json app.use(serve('.')); // $ GET /hello.txt app.use(serve('test/fixtures')); // or use absolute paths app.use(serve(__dirname + '/test/fixtures')); app.listen(3000); console.log('listening on port 3000'); ~~~ # [koa-session](https://github.com/koajs/session) HTTP是無狀態協議,為了保持用戶狀態,我們一般使用Session會話,koa-session提供了這樣的功能,既支持將會話信息存儲在本地Cookie,也支持存儲在如Redis, MongoDB這樣的外部存儲設備。 ## Example View counter example: ~~~js const session = require('koa-session'); const Koa = require('koa'); const app = new Koa(); app.keys = ['some secret hurr']; const CONFIG = { key: 'koa:sess', /** (string) cookie key (default is koa:sess) */ /** (number || 'session') maxAge in ms (default is 1 days) */ /** 'session' will result in a cookie that expires when session/browser is closed */ /** Warning: If a session cookie is stolen, this cookie will never expire */ maxAge: 86400000, autoCommit: true, /** (boolean) automatically commit headers (default true) */ overwrite: true, /** (boolean) can overwrite or not (default true) */ httpOnly: true, /** (boolean) httpOnly or not (default true) */ signed: true, /** (boolean) signed or not (default true) */ rolling: false, /** (boolean) Force a session identifier cookie to be set on every response. The expiration is reset to the original maxAge, resetting the expiration countdown. (default is false) */ renew: false, /** (boolean) renew session when session is nearly expired, so we can always keep user logged in. (default is false)*/ }; app.use(session(CONFIG, app)); // or if you prefer all default config, just use => app.use(session(app)); app.use(ctx => { // ignore favicon if (ctx.path === '/favicon.ico') return; let n = ctx.session.views || 0; ctx.session.views = ++n; ctx.body = n + ' views'; }); app.listen(3000); console.log('listening on port 3000'); ~~~ # [koa-jwt](https://github.com/koajs/jwt) 隨著網站前后端分離方案的流行,越來越多的網站從Session Base轉為使用Token Base,JWT(Json Web Tokens)作為一個開放的標準被很多網站采用,koa-jwt這個中間件使用JWT認證HTTP請求。 ## Example ~~~js var Koa = require('koa'); var jwt = require('koa-jwt'); var app = new Koa(); // Custom 401 handling if you don't want to expose koa-jwt errors to users app.use(function(ctx, next){ return next().catch((err) => { if (401 == err.status) { ctx.status = 401; ctx.body = 'Protected resource, use Authorization header to get access\n'; } else { throw err; } }); }); // Unprotected middleware app.use(function(ctx, next){ if (ctx.url.match(/^\/public/)) { ctx.body = 'unprotected\n'; } else { return next(); } }); // Middleware below this line is only reached if JWT token is valid app.use(jwt({ secret: 'shared-secret' })); // Protected middleware app.use(function(ctx){ if (ctx.url.match(/^\/api/)) { ctx.body = 'protected\n'; } }); app.listen(3000); ~~~ Alternatively you can conditionally run the`jwt`middleware under certain conditions: ~~~js var koa = require('koa'); var jwt = require('koa-jwt'); var app = new Koa(); // Middleware below this line is only reached if JWT token is valid // unless the URL starts with '/public' app.use(jwt({ secret: 'shared-secret' }).unless({ path: [/^\/public/] })); // Unprotected middleware app.use(function(ctx, next){ if (ctx.url.match(/^\/public/)) { ctx.body = 'unprotected\n'; } else { return next(); } }); // Protected middleware app.use(function(ctx){ if (ctx.url.match(/^\/api/)) { ctx.body = 'protected\n'; } }); app.listen(3000); ~~~ # [koa-helmet](https://github.com/venables/koa-helmet) 網絡安全得到越來越多的重視,koa-helmet 通過增加如Strict-Transport-Security, X-Frame-Options, X-Frame-Options等HTTP頭提高Koa應用程序的安全性。 ## Example ~~~js "use strict"; const Koa = require("koa"); const helmet = require("koa-helmet"); const app = new Koa(); app.use(helmet()); app.use((ctx) => { ctx.body = "Hello World" }); app.listen(4000); ~~~ # [koa-compress](https://github.com/koajs/compress) 當響應體比較大時,我們一般會啟用類似Gzip的壓縮技術減少傳輸內容,koa-compress提供了這樣的功能,可根據需要進行靈活的配置。 ## Example ~~~js var compress = require('koa-compress') var Koa = require('koa') var app = new Koa() app.use(compress({ filter: function (content_type) { return /text/i.test(content_type) }, threshold: 2048, flush: require('zlib').Z_SYNC_FLUSH })) ~~~ # [koa-logger](https://github.com/koajs/logger) koa-logger提供了輸出請求日志的功能,包括請求的url、狀態碼、響應時間、響應體大小等信息,對于調試和跟蹤應用程序特別有幫助。 ## Example ~~~js const logger = require('koa-logger') const Koa = require('koa') const app = new Koa() app.use(logger()) ~~~ # @koa/cors ## Installation ~~~shell $ npm install @koa/cors@2 --save ~~~ ## Quick start Enable cors with default options: * origin: request Origin header * allowMethods: GET,HEAD,PUT,POST,DELETE,PATCH ~~~js const Koa = require('koa'); const cors = require('@koa/cors'); const app = new Koa(); app.use(cors()); ~~~ # moment 時間格式化 `https://www.npmjs.com/package/moment`
                  <ruby id="bdb3f"></ruby>

                  <p id="bdb3f"><cite id="bdb3f"></cite></p>

                    <p id="bdb3f"><cite id="bdb3f"><th id="bdb3f"></th></cite></p><p id="bdb3f"></p>
                      <p id="bdb3f"><cite id="bdb3f"></cite></p>

                        <pre id="bdb3f"></pre>
                        <pre id="bdb3f"><del id="bdb3f"><thead id="bdb3f"></thead></del></pre>

                        <ruby id="bdb3f"><mark id="bdb3f"></mark></ruby><ruby id="bdb3f"></ruby>
                        <pre id="bdb3f"><pre id="bdb3f"><mark id="bdb3f"></mark></pre></pre><output id="bdb3f"></output><p id="bdb3f"></p><p id="bdb3f"></p>

                        <pre id="bdb3f"><del id="bdb3f"><progress id="bdb3f"></progress></del></pre>

                              <ruby id="bdb3f"></ruby>

                              哎呀哎呀视频在线观看