URL 參數傳遞時,`&`、`=`、`?`、`#`、空格、中文等特殊字元若不正確編碼,會導致參數截斷、解析錯誤或安全漏洞。本文詳細說明前後端編碼/解碼策略與最佳實踐。
// 錯誤範例:cn 參數值包含 "&"
const url = 'groupsDetailServlet?groupType=A&cn=AT&T';
// 實際解析:groupType=A, cn=AT, T=undefined
function buildUrl(base, params) {
const search = new URLSearchParams();
Object.entries(params).forEach(([k, v]) => search.append(k, v));
return `${base}?${search.toString()}`;
}
// 使用
const url = buildUrl('groupsDetailServlet', {
groupTypeForDetail: 'A',
cn: 'AT&T' // 自動編碼為 AT%26T
});
location.href = url; // groupsDetailServlet?groupTypeForDetail=A&cn=AT%26T
優點: 符合 RFC 3986、處理所有保留字元、支援 Unicode、現代瀏覽器原生支援。
const url = 'https://example.com/search?q=hello world';
encodeURI(url); // "https://example.com/search?q=hello%20world"
// 注意:不編碼 & = ? # 等保留字元,不適合編碼單一參數值
不編碼 `+`、`@`、`*`、`/` 等,編碼方式非標準(`%uXXXX`),現代環境請改用 `encodeURIComponent`。
// 編碼
String encoded = URLEncoder.encode(cn, StandardCharsets.UTF_8);
// AT&T → AT%26T
// 解碼
String decoded = URLDecoder.decode(encoded, StandardCharsets.UTF_8);
// 編碼
string encoded = Uri.EscapeDataString(cn); // 或 HttpUtility.UrlEncode
// 解碼
string decoded = Uri.UnescapeDataString(encoded);
const querystring = require('querystring');
const encoded = querystring.escape('AT&T'); // 'AT%26T'
const decoded = querystring.unescape(encoded);
若舊系統無法使用標準編碼,可約定替代字元(如 `@` 代替 `&`),但**強烈不建議**新專案採用:
// 編碼
function customEncode(str) {
return str.replace(/&/g, '@@'); // 雙 @ 避免衝突
}
// 解碼
function customDecode(str) {
return str.replace(/@@/g, '&');
}
const apiBase = 'https://api.example.com';
const url = new URL('/groups/detail', apiBase);
url.searchParams.set('groupType', 'A');
url.searchParams.set('cn', 'AT&T'); // 自動編碼
console.log(url.href); // https://api.example.com/groups/detail?groupType=A&cn=AT%26T
// 解析現有 URL
const parsed = new URL(window.location.href);
const cn = parsed.searchParams.get('cn'); // 自動解碼 → "AT&T"
// ASP.NET Core
[HttpGet("groups/detail")]
public IActionResult Detail(string groupType, string cn) {
// cn 已自動解碼為 "AT&T"
}
// Spring Boot
@GetMapping("/groups/detail")
public ResponseEntity> detail(@RequestParam String groupType, @RequestParam String cn) {
// cn 已自動解碼
}
// Express.js
app.get('/groups/detail', (req, res) => {
const { groupType, cn } = req.query; // 已自動解碼
});
| 情境 | 錯誤做法 | 正確做法 |
|---|---|---|
| 拼接查詢字串 | `'?a=' + val` | `new URLSearchParams({a: val}).toString()` |
| 已編碼字串再編碼 | `encodeURIComponent(encodeURIComponent(val))` | 僅編碼一次 |
| 表單提交 | 手動拼接 | ` |
| 中文參數 | 依賴瀏覽器預設編碼 | 明確指定 UTF-8,使用 `encodeURIComponent` |
| 雙重編碼 | 前端編碼 + 後端再編碼 | 約定單邊負責,通常前端編碼、後端解碼 |
標準化編碼/解碼流程,能從根源杜絕參數截斷、亂碼、注入等經典 Bug。