node js(模塊)

  • koa-router模塊

    • 和koa-route模塊一樣,也是koa的一個中間,用來處理路由

    • 下載

      • cnpm i koa-router -S
        
    • 使用

      • const Koa = require('koa');
        const Router = require('koa-router');
        const app = new Koa();
        const router = new Router();
        const main = ctx => {
          ctx.body = 'Hello Koa';
        }
        router.get('/', main);
        // 注冊并使用routers啟動路由
        app.use(router.routes())
        // 自動豐富response相應(yīng)頭,當(dāng)未設(shè)置響應(yīng)狀態(tài)的時候自動設(shè)置,在所有路由中間件最后設(shè)置,也可以設(shè)置具體某一個路由,例如:router.get('/index', router.allowedMethods());這相當(dāng)于當(dāng)訪問/index時才設(shè)置
        .use(router.allowedMethods())
        .listen(3000);
        
      • 參數(shù)處理

      • const Koa = require('koa');
        const Router = require('koa-router');
        const app = new Koa();
        const router = new Router();
        // 單個參數(shù)
        const main = ctx => {
          // http://127.0.0.1:3000/123
          console.log(ctx.params); // {id: 123}
          ctx.body = 'Hello Koa';
        }
        // 多個參數(shù)
        //const main = ctx => {
          // http://127.0.0.1:3000/123/456
          //console.log(ctx.params); // {id: 123, uid: 456}
          //ctx.body = 'Hello Koa';
        //}
        router.get('/:id/:uid', main);
        // 注冊并使用routers啟動路由
        app.use(router.routes())
        .use(router.allowedMethods())
        .listen(3000);
        
      • 路由封裝

        • 當(dāng)項目龐大,路由非常多時,app.js就會變得特別臃腫
      • 例:index.js

      • const Router = require('koa-router');
        const router = new Router();
        router.get('/', (ctx, next) => {
          ctx.body = 'index';
          // next()函數(shù),當(dāng)執(zhí)行next將會從這里主動把執(zhí)行權(quán)交給下一個中間件
          next();
        });
        module.exports = router.routes();
        
      • 總路由配置文件router.js

      • const Router = require('koa-router');
        const router = new Router();
        const index = require('./routes/index.js');
        const about = require('./routes/about.js');
        router.use('/', index);
        router.use('/about', about);
        module.exports = router;
        
      • app.js

      • const router = require('./router.js');
        app.use(router.routes())
        .use(router.allowedMethods())
        .listen(3000);
        
  • koa-bodyparser模塊

    • 處理post請求的上下文注入到ctx.req.body中

    • const Koa = require('koa');
      const Router = require('koa-router');
      const app = new Koa();
      const router = new Router();
      const bodyParser = require('koa-bodyparser');
      app.use(bodyParser);
      router.post('/', ctx => {
        console.log(ctx.req.body)
      });
      app.use(router.routes());
      app.listen(3000);
      
  • koa-views模塊、ejs模塊

    • koa-views處理模板

    • ejs模板引擎

    • const Koa = require('koa');
      const app = new Koa();
      const views = require('koa-views');
      const path = require('path');
      app.use(views(path(__dirname, 'views'), {
        extension: 'ejs'
      })
      app.use(ctx => {
          let title = 'hello ejs';
          ctx.render('index', {title})
      })      
      
    • views/index.ejs

    • <!DOCTYPE html>
      <html>
          <head>
              <title><%= title%></title>
          </head>
      </html>
      
  • 請求頭設(shè)置及說明

    • CORS

      • CORS是一個W3C標(biāo)準(zhǔn),全稱是"跨域資源共享(Cross-origin resource sharing)

      • const Koa = require('koa');
        const app = new Koa();
        router.get('/', ctx => {
          // 允許所有域請求
          ctx.set("Access-Control-Allow-Origin", "*");
          // 只允許來自http://localhost:8080的請求
          ctx.set("Access-Control-Allow-Origin", "http://localhost:8080");
          // 設(shè)置所允許的HTTP請求方法
          ctx.set("Access-Control-Allow-Methods", "OPTIONS, GET, PUT, POST, DELETE");
          // 表明服務(wù)器支持的所有頭信息字段.
          ctx.set("Access-Control-Allow-Headers", "x-requested-with, accept, origin, content-type");
          // Content-Type表示具體請求中的媒體類型信息
          ctx.set("Content-Type", "application/json;charset=utf-8");
          // 該字段可選。它的值是一個布爾值,表示是否允許發(fā)送Cookie。默認(rèn)情況下,Cookie不包括在CORS請求之中。
          // 當(dāng)設(shè)置成允許請求攜帶cookie時,需要保證"Access-Control-Allow-Origin"是服務(wù)器有的域名,而不能是"*";
          ctx.set("Access-Control-Allow-Credentials", true);
        });
        app.use(router.routes());
        app.listen(3000);
        
    • form表單

      • method

        • 請求方式,一般使用get和post
      • enctype

        • application/x-www-form-urlencoded
          • 對所有字符都會進(jìn)行編碼(空格轉(zhuǎn)換為 "+" 加號,特殊符號轉(zhuǎn)換為 ASCII HEX 值)
        • multipart/form-data
          • 不對字符編碼。在使用包含文件上傳控件的表單時,必須使用該值
        • text/plain
          • 空格轉(zhuǎn)換為 "+" 加號,但不對特殊字符編碼
      • action

        • 請求地址
      • name

        • 設(shè)置表單名稱
      • novalidate

        • 阻止表單默認(rèn)的驗證規(guī)則,否則會與開發(fā)中的驗證規(guī)則發(fā)生沖突,建議添加
      • 阻止表單默認(rèn)跳轉(zhuǎn)

        • ev.preventDefault(),但是同時會阻止表單的默認(rèn)提交

        • 通過iframe阻止跳轉(zhuǎn),調(diào)用form的submit方法,可以達(dá)到提交數(shù)據(jù)并且不會跳轉(zhuǎn)的目的

        • <form action="url" target="stop"></form>
          <iframe name="stop" style="display:none;"></iframe>
          
      • 獲取form表單提交后,獲取后端返回的數(shù)據(jù)

        • 常見的獲取方式是通過jquery的ajaxForm,但是我們往往不會因為一個功能點(diǎn)而去增加項目的重量,這是不合理的,這里我們通過原生來實現(xiàn)這個功能,我們通過iframe阻止跳轉(zhuǎn)是因為我們的form指向了我們的iframe,請求后端后,后端返回數(shù)據(jù)也就指向了我們的iframe

        • <form action="url" target="stop"></form>
          <iframe name="stop" style="display:none;" id="formData"></iframe>
          
        • javascript

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

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

  • 本文由郝晨光整理總結(jié)并編寫,未經(jīng)允許禁止轉(zhuǎn)載。 前言 學(xué)習(xí)koa,我之前學(xué)習(xí)過express,但是在使用expre...
    郝晨光閱讀 1,364評論 0 12
  • koa-session模塊下載npm install koa-session --save配置const sess...
    Sun晨淏閱讀 428評論 0 0
  • 一、基本用法 1.1 架設(shè) HTTP 服務(wù) // demos/01.jsconst Koa = require('...
    majun00閱讀 1,544評論 0 5
  • 框架是一種概念,是對常見功能的封裝,是整個或部分系統(tǒng)的可重用設(shè)計,表現(xiàn)為一組抽象構(gòu)件及構(gòu)件實例間交互的方法,通過制...
    Sun晨淏閱讀 583評論 0 1
  • 使用Koa搭建 基礎(chǔ)項目 一、創(chuàng)建項目 手動創(chuàng)建一個項目目錄,然后快速生成一個 package.json 文件np...
    隨風(fēng)飛2019閱讀 1,575評論 0 6

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