本文主要是對connect-history-api-fallback
庫進行一次源碼分析。connect-history-api-fallback
是一個用於支持SPA History路由模式的nodejs
庫。閱讀本文前,應對HTML5 History
模式有必定程度的瞭解!html
/** * 前端須要開啓history模式,然後端根據url並不知道前端在請求api仍是在請求頁面,如localhost:4200/home這種url,前端理所固然認爲「我須要獲得html,並跳轉到首頁」,然然後端並不能區分。 * 所以須要一種判斷機制,來使得後端能分析出前端的請求目的。 * connect-history-api-fallback 這個中間件正好幫咱們完成了上述分析操做,來看下它是怎麼實現的吧! * 第一次把本身的源碼分析思路寫出來,說得不對的地方,請指出! */ 'use strict'; var url = require('url'); exports = module.exports = function historyApiFallback(options) { // 接收配置參數 options = options || {}; // 初始化日誌管理器 var logger = getLogger(options); // 中間件是要返回一個函數的,函數形參有req, res, next return function(req, res, next) { var headers = req.headers; if (req.method !== 'GET') { // 若是請求方法不是GET類型,說明不須要返回html,那麼就調用next(),把請求交給下一個中間件 logger( 'Not rewriting', req.method, req.url, 'because the method is not GET.' ); return next(); } else if (!headers || typeof headers.accept !== 'string') { // 若是沒有請求頭,或者請求頭中的accept不是字符串,說明不是一個標準的http請求,也不予處理,把請求交給下一個中間件 logger( 'Not rewriting', req.method, req.url, 'because the client did not send an HTTP accept header.' ); return next(); } else if (headers.accept.indexOf('application/json') === 0) { // 若是客戶端但願獲得application/json類型的響應,說明也不是在請求html,也不予處理,把請求交給下一個中間件 logger( 'Not rewriting', req.method, req.url, 'because the client prefers JSON.' ); return next(); } else if (!acceptsHtml(headers.accept, options)) { // 若是請求頭中不包含配置的Accept或者默認的['text/html', '*/*'],那麼說明也不是在請求html,也不予處理,把請求交給下一個中間件 logger( 'Not rewriting', req.method, req.url, 'because the client does not accept HTML.' ); return next(); } // 走到這裏說明是在請求html了,要開始秀操做了 // 首先利用url模塊的parse方法解析下url,會獲得一個對象,包括protocol,hash,path, pathname, query, search等字段,相似瀏覽器的location對象 var parsedUrl = url.parse(req.url); var rewriteTarget; // 而後獲得配置中的rewrites,也就是重定向配置; // 重定向配置是一個數組,每一項都包含from和to兩個屬性; // from是用來正則匹配pathname是否須要重定向的; // to則是重定向的url,to能夠是一個字符串,也能夠是一個回調方法來返回一個字符串,回調函數接收一個上下文參數context,context包含三個屬性(parsedUrl,match,request) options.rewrites = options.rewrites || []; // 遍歷一波重定向配置 for (var i = 0; i < options.rewrites.length; i++) { var rewrite = options.rewrites[i]; // 利用字符串的match方法去匹配 var match = parsedUrl.pathname.match(rewrite.from); if (match !== null) { // 若是match不是null,說明pathname和重定向配置匹配上了 rewriteTarget = evaluateRewriteRule(parsedUrl, match, rewrite.to, req); if(rewriteTarget.charAt(0) !== '/') { // 推薦使用/開頭的絕對路徑做爲重定向url logger( 'We recommend using an absolute path for the rewrite target.', 'Received a non-absolute rewrite target', rewriteTarget, 'for URL', req.url ); } logger('Rewriting', req.method, req.url, 'to', rewriteTarget); // 進行重定向url操做 req.url = rewriteTarget; return next(); } } var pathname = parsedUrl.pathname; // 首先說明一下:校驗邏輯默認是會去檢查url中最後的.號的,有.號的說明在請求文件,那就跟history模式就沒什麼鳥關係了 // 我暫且將上述規則成爲「點號校驗規則」 // disableDotRule爲true,表明禁用點號校驗規則 if (pathname.lastIndexOf('.') > pathname.lastIndexOf('/') && options.disableDotRule !== true) { // 若是pathname的最後一個/以後還有.,說明請求的是/a/b/c/d.*的文件(*表明任意文件類型); // 若是此時配置disableDotRule爲false,說明開啓點號校驗規則,那麼不予處理,交給其餘中間件 logger( 'Not rewriting', req.method, req.url, 'because the path includes a dot (.) character.' ); return next(); } // 若是pathname最後一個/以後沒有.,或者disableDotRule爲true,都會走到最後一步:重寫url // 重寫url有默認值/index.html,也能夠經過配置中的index自定義 rewriteTarget = options.index || '/index.html'; logger('Rewriting', req.method, req.url, 'to', rewriteTarget); // 重寫url req.url = rewriteTarget; // 此時再將執行權交給下一個中間件(url都換成index.html了,後面的路由等中間件也不會再處理了,而後前端接收到html就開始解析路由了,目的達到!) next(); }; }; // 判斷重定向配置中的to function evaluateRewriteRule(parsedUrl, match, rule, req) { if (typeof rule === 'string') { // 若是是字符串,直接返回 return rule; } else if (typeof rule !== 'function') { // 若是不是函數,拋出錯誤 throw new Error('Rewrite rule can only be of type string or function.'); } // 執行自定義的回調函數,獲得一個重定向的url return rule({ parsedUrl: parsedUrl, match: match, request: req }); } // 判斷請求頭的accept是否是包含在配置數組或默認數組的範圍內 function acceptsHtml(header, options) { options.htmlAcceptHeaders = options.htmlAcceptHeaders || ['text/html', '*/*']; for (var i = 0; i < options.htmlAcceptHeaders.length; i++) { if (header.indexOf(options.htmlAcceptHeaders[i]) !== -1) { return true; } } return false; } // 處理日誌 function getLogger(options) { if (options && options.logger) { // 若是有指定的日誌方法,則使用指定的日誌方法 return options.logger; } else if (options && options.verbose) { // 不然,若是配置了verbose,默認使用console.log做爲日誌方法 return console.log.bind(console); } // 不然就沒有日誌方法,就不記錄日誌咯 return function(){}; }