上次工做中遇到一個場景:傳參是一個完成的URL,而直接把URL傳過去明顯是行不通的,由於URL上有一些字符是有特殊意義的,並且也有可能url會存在中文等狀況,會變得很是不可控,因此URL須要字符編碼處理,再進行傳參。 以前沒有細想,可是爲了加深理解、記憶,我把這方面也寫下來。api
訪問連接 https://www.xiaoyexiang.com/oauth2/authorize?redirect_uri={url}
,{url}
是一個連接參數。應爲https://api.xiaoyexiang.com/api/weixin/login/oauth2?next=https://www.xiaoyexiang.com/classroom/home
bash
剛開始我是使用了 encodeURI()
來處理URL,發現並無什麼效果:函數
let loginUrl = 'https://www.xiaoyexiang.com/oauth2/authorize?redirect_uri={redirect_uri}';
const originUri = `https://api.xiaoyexiang.com/api/weixin/login/oauth2?next=https://wwww.xiaoyexiang.com/l/s/352?_source=index_rcmd`;
const encodedUrl = encodeURI(originUri);
loginUrl = loginUrl.replace('{redirect_uri}', encodedUrl);
console.log(loginUrl);
// https://www.xiaoyexiang.com/oauth2/authorize?redirect_uri=https://api.xiaoyexiang.com/api/weixin/login/oauth2?next=https://wwww.xiaoyexiang.com/l/s/352?_source=index_rcmd
console.log(encodedUrl);
// https://api.xiaoyexiang.com/api/weixin/login/oauth2?next=https://wwww.xiaoyexiang.com/l/s/352?_source=index_rcmd
複製代碼
後來查閱資料改用 encodeURIComponent()
:ui
let loginUrl = 'https://www.xiaoyexiang.com/oauth2/authorize?redirect_uri={redirect_uri}';
const originUri = `https://api.xiaoyexiang.com/api/weixin/login/oauth2?next=https://wwww.xiaoyexiang.com/l/s/352?_source=index_rcmd`;
const encodedUrl = encodeURIComponent(originUri);
loginUrl = loginUrl.replace('{redirect_uri}', encodedUrl);
console.log(loginUrl);
// https://www.xiaoyexiang.com/oauth2/authorize?redirect_uri=https%3A%2F%2Fapi.xiaoyexiang.com%2Fapi%2Fweixin%2Flogin%2Foauth2%3Fnext%3Dhttps%3A%2F%2Fwwww.xiaoyexiang.com%2Fl%2Fs%2F352%3F_source%3Dindex_rcmd
console.log(encodedUrl);
// https%3A%2F%2Fapi.xiaoyexiang.com%2Fapi%2Fweixin%2Flogin%2Foauth2%3Fnext%3Dhttps%3A%2F%2Fwwww.xiaoyexiang.com%2Fl%2Fs%2F352%3F_source%3Dindex_rcmd
複製代碼
都是用來編碼和解碼URI的。編碼
函數解碼一個由encodeURI 先前建立的統一資源標識符(URI)或相似的例程。url
(
、)
、.
、!
、~
、*
、'
、-
和_
以外的全部方法用於解碼由 encodeURIComponent 方法或者其它相似方法編碼的部分統一資源標識符(URI)。spa
當你須要轉碼/解碼的URL是須要一個完整、可直接訪問的URL時,應該使用encodeURI/decodeURI; 當你須要轉碼/解碼的URL是做爲連接的一部分,好比用做參數的狀況,應該使用encodeURIComponent/decodeURIComponentssr