使用decodeURIComponent解码GBK编码的URL出现URI malformed错误,Nodejs求解决方法
使用decodeURIComponent解码GBK编码的URL出现URI malformed错误,Nodejs求解决方法
var a = ‘%CC%EC%D4%DE%D6%FA%BB%E1%D4%B1%C9%ED%B7%DD’;
/Users/liurex/Documents/ShopService/app.js:49 var ccc = decodeURIComponent(a); ^ URIError: URI malformed
在使用 Node.js 处理 URL 编码时,decodeURIComponent
默认处理的是 UTF-8 编码。如果你尝试解码GBK编码的字符串,可能会遇到 URIError: URI malformed
错误。这是因为 decodeURIComponent
并不支持GBK编码。
为了解决这个问题,你可以先将GBK编码转换为UTF-8编码,然后再进行解码。这可以通过使用第三方库如 iconv-lite
来实现。以下是一个完整的解决方案:
步骤1:安装 iconv-lite
库
首先,你需要安装 iconv-lite
库。可以通过 npm 安装:
npm install iconv-lite
步骤2:编写代码
接下来,你可以使用 iconv-lite
将GBK编码转换为UTF-8编码,然后使用 decodeURIComponent
进行解码。以下是一个示例代码:
const iconv = require('iconv-lite');
// 原始的GBK编码字符串
var a = '%CC%EC%D4%DE%D6%FA%BB%E1%D4%B1%C9%ED%B7%DD';
// 先将十六进制字符串转换为Buffer对象
var buffer = Buffer.from(a, 'hex');
// 使用iconv-lite将GBK编码转换为UTF-8编码
var utf8String = iconv.decode(buffer, 'gbk');
// 解码后的字符串
console.log(utf8String);
// 输出结果
// 输出类似于:出席活动员工出差
解释
- Buffer.from(a, ‘hex’): 将十六进制字符串转换为
Buffer
对象。 - iconv.decode(buffer, ‘gbk’): 使用
iconv-lite
将Buffer
对象从GBK编码转换为UTF-8编码。 - decodeURIComponent(utf8String): 使用
decodeURIComponent
对UTF-8编码的字符串进行解码。
通过这种方式,你就可以正确地处理GBK编码的URL,并避免 URIError: URI malformed
错误。
你自己写个程序转换
没有现成的模块么?
如果只限于nodejs平台,可利用已有的gbk->unicode模块
//npm install iconv-lite
var iconv=require('iconv-lite');
var a = '%CC%EC%D4%DE%D6%FA%BB%E1%D4%B1%C9%ED%B7%DD';
a=a.replace(/%([a-zA-Z0-9]{2})/g,function(_,code){
return String.fromCharCode(parseInt(code,16));
});
var buff=new Buffer(a,'binary');
var result=iconv.decode(buff,'gbk');
console.log(result);
如果要在浏览器端跑,楼上童鞋正解
在Node.js中,decodeURIComponent
函数默认是基于UTF-8进行解码的,而你的字符串是用GBK编码的。因此,直接使用 decodeURIComponent
会导致 URIError: URI malformed
错误。
为了解决这个问题,你可以先将GBK编码转换成UTF-8,然后再进行解码。这里提供一个示例代码,展示了如何使用 iconv-lite
库来处理GBK编码:
const iconv = require('iconv-lite');
var a = '%CC%EC%D4%DE%D6%FA%BB%E1%D4%B1%C9%ED%B7%DD';
// 将百分号编码的字符串解码成二进制数据
var binaryData = Buffer.from(a, 'binary');
// 使用iconv-lite库将二进制数据从GBK转换成UTF-8
var utf8String = iconv.decode(binaryData, 'gbk');
// 然后可以安全地使用decodeURIComponent进行解码
var decodedString = decodeURIComponent(utf8String);
console.log(decodedString); // 输出解码后的字符串
确保你已经安装了 iconv-lite
库,可以通过以下命令安装:
npm install iconv-lite
通过上述步骤,你可以正确地将GBK编码的URL解码为所需的字符串。这样可以避免 URIError: URI malformed
错误。