昨天剛剛發(fā)表了一個前端跨域新方案嘗試,今天在開發(fā)中就遇到的了問題。
起因
前端使用的是vue-router組件的history模式,但是由于我們的整個頁面都是從static(靜態(tài)資源站)load過來的,所以其他頁面自然也需要跨域去拿,然而就在跨域的時候 vue-router 出了問題。
分析問題
我們的api站點在 api.com
而靜態(tài)資源在 static.com,頁面的base標簽也指向static
<base rel="external nofollow" />
然而,在訪問 test模板時卻跳到了http://api.com/http:/static.com/test
經(jīng)過一些簡單的斷點調(diào)試,鎖定了以下代碼
[source]: https://github.com/vuejs/vue-router/blob/dev/dist/vue-router.esm.js
[vue-router.esm.js][source]
//1794行~1675行function normalizeBase (base) { if (!base) { if (inBrowser) { // respect <base> tag var baseEl = document.querySelector('base'); base = (baseEl && baseEl.getAttribute('href')) || '/'; } else { base = '/'; } } // make sure there's the starting slash if (base.charAt(0) !== '/') { base = '/' + base; } // remove trailing slash return base.replace(///$/, '')}這段代碼的作用是設置路由的base路徑,如果有興趣一路跟蹤的話會發(fā)現(xiàn)這個base參數(shù)是由實例化VueRouter時候傳入的options.base;
再看代碼,他會判斷如果base是空的,那么就會給一個默認值:
如果實在瀏覽器(非服務器環(huán)境)下執(zhí)行,那么會調(diào)用document.querySelector('base')來嘗試獲取<base href='' />標簽中href屬性的值;
在我們實際的場景中,這里得到一個跨域的絕對地址,然后緊接著
if (base.charAt(0) !== '/') { base = '/' + base; }當url第一個字符不是/的時候加上/,這里非常明顯是一個BUG
我的是絕對地址http://static.com第一個字符當然不是/,所以才會由之前的http://api.com/http:/static.com/test這樣的網(wǎng)址
修改
if(/^([a-z]+:)?/////i.test(base)){}else if (base.charAt(0) !== '/') { base = '/' + base;}為了盡量少破壞源碼,這里加了一個空的if,當url是由協(xié)議開始時,認為是絕對路徑。
* 絕對路徑還有一種形式是 //static.com
測試
經(jīng)過第一次修改,再次訪問頁面依然有問題,訪問的頁面依然是http://api.com/http:/static.com/test
繼續(xù)分析
再次跟蹤源碼后發(fā)現(xiàn)
[vue-router.esm.js][source]
//2006行~2016行 HTML5History.prototype.push = function push (location, onComplete, onAbort) { var this$1 = this; var ref = this; var fromRoute = ref.current; this.transitionTo(location, function (route) { pushState(cleanPath(this$1.base + route.fullPath)); handleScroll(this$1.router, route, fromRoute, false); onComplete && onComplete(route); }, onAbort); };//561行~563行function cleanPath (path) { return path.replace(//////g, '/')}
|
新聞熱點
疑難解答
圖片精選