昨天剛剛發表了一個前端跨域新方案嘗試,今天在開發中就遇到的了問題。
起因
前端使用的是vue-router組件的history
模式,但是由於我們的整個頁面都是從static(靜態資源站)load過來的,所以其他頁面自然也需要跨域去拿,然而就在跨域的時候 vue-router 出了問題。
分析問題
我們的api站點在 api.com
而靜態資源在 static.com,頁面的base標簽也指向static
<base href="http://static.com" />
然而,在訪問 test
模板時卻跳到了http://api.com/http:/static.com/test
經過一些簡單的斷點調試,鎖定了以下代碼
[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路徑,如果有興趣一路跟蹤的話會發現這個base
參數是由實例化VueRouter
時候傳入的options.base
;
再看代碼,他會判斷如果base是空的,那么就會給一個默認值:
如果實在瀏覽器(非服務器環境)下執行,那么會調用document.querySelector('base')
來嘗試獲取<base href='' />
標簽中href
屬性的值;
在我們實際的場景中,這里得到一個跨域的絕對地址,然后緊接着
if (base.charAt(0) !== '/') {
base = '/' + base;
}
當url第一個字符不是/
的時候加上/
,這里非常明顯是一個BUG
我的是絕對地址http://static.com
第一個字符當然不是/
,
所以才會由之前的http://api.com/http:/static.com/test
這樣的網址
修改
if(/^([a-z]+:)?\/\//i.test(base)){
}else if (base.charAt(0) !== '/') {
base = '/' + base;
}
為了盡量少破壞源碼,這里加了一個空的if,當url是由協議開始時,認為是絕對路徑。
* 絕對路徑還有一種形式是 //static.com
測試
經過第一次修改,再次訪問頁面依然有問題,訪問的頁面依然是http://api.com/http:/static.com/test
繼續分析
再次跟蹤源碼后發現
[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, '/')
}
在發生pushState
之前,他還會對url再次進行處理cleanPath
而這里的處理更簡單,更粗暴,問題也更大。
他直接將2個斜杠//
替換為1個斜杠/
,話說如果連續3個斜杠怎么辦?
所以在處理http://static.com/test
地址的時候,其實會被處理成http:/static.com/test
又變成相對路徑了...
繼續修改
function cleanPath (path) {
var ishttp = /^([a-z]+:)?\/\//i.exec(path);
var http = Array.isArray(ishttp) ? ishttp[0] : '';
return http + path.substr(http.length).replace(/\/{2,}/g, '/');
}
如果是協議開始,則排除協議內容之后,將2個或2個以上連續在一起的斜杠替換為1個斜杠。
** 完成提交pull
https://github.com/vuejs/vue-router/pull/1353/files
話說vue-router的url處理比起Url.js來說真的是太粗暴了...