URL 中传递参数时出现中文乱码的问题通常是由于编码和解码不一致导致的。以下是关于这个问题的基础概念、原因、解决方案以及相关示例代码。
当在 URL 中传递中文参数时,如果没有正确进行 URL 编码,浏览器会使用默认的编码方式(可能是 GBK 或其他),导致接收端解码时出现乱码。
// 假设有一个中文参数
let chineseParam = "你好";
// 使用 encodeURIComponent 进行 URL 编码
let encodedParam = encodeURIComponent(chineseParam);
// 构造完整的 URL
let url = `http://example.com/api?param=${encodedParam}`;
// 发送请求(例如使用 fetch)
fetch(url)
.then(response => response.json())
.then(data => console.log(data))
.catch(error => console.error('Error:', error));
const http = require('http');
const url = require('url');
http.createServer((req, res) => {
const queryObject = url.parse(req.url, true).query;
const decodedParam = decodeURIComponent(queryObject.param);
console.log('Received parameter:', decodedParam); // 应该正确显示 "你好"
res.writeHead(200, {'Content-Type': 'application/json'});
res.end(JSON.stringify({received: decodedParam}));
}).listen(3000);
通过上述方法,可以有效避免 URL 传递中文参数时的乱码问题。确保前后端都使用相同的编码和解码方式是关键。
领取专属 10元无门槛券
手把手带您无忧上云