JavaScript:将字符集从非标准字符集转换为 UTF-8

问题描述

有一个带有 <meta charset="EUC-KR"> 的页面,比如 address-search.foo.com,它搜索一个地址并将其发送到指定的 url,通过提交 POST 方法的 html 形式,如下所示。

let form = <form element>;
form.zipCode.value = "63563";
form.address.value = "제주특별자치도 서귀포시 이어도로 579 (강정동)";
form.action = "https://my-service.foo.com";
form.method = "post";
form.submit();

并且在 my-service.foo.com 中有一个由 ExpressJs 运行的 POST 处理程序来处理上面的请求,如下所示。

const next = require("next");
const app = next(nextConfig);

const server = express();
server.use(bodyParser.urlencoded({ extended: false }));
server.use(bodyParser.json());

server.post("/",(req,res) => {
  console.log(req.body);

  app.render(req,res,"/");
});

还有 console.log(req.body);上面打印下面。

[Object: null prototype] {
  zipCode: '63563'
  address: '����Ư����ġ�� �������� �̾�� 579 (������)'
}

我尝试使用 req.body.address 模块转换 iconv-lite 的编码,但它不像在 PHP 上那样工作,如下所示。

iconv("CP949","UTF-8",$_POST['address']); // working very happily

如何正确使用 iconv-lite 或者有没有办法在 ExpressJs 上解决这个问题?

解决方法

使用 urlencode 模块。

我使用 bodyParser.raw() 而不是 bodyParser.urlencoded() 解决了这个问题。

const urlencode = require("urlencode");
const iconv = require("iconv-lite");
const qs = require("querystring");

server.use(
  bodyParser.raw({ type: "application/x-www-form-urlencoded" }),(req,res,next) => {
    if (req.method === "POST") {
      const decoded = iconv.decode(req.body,"utf8");
      /**
       * Define another conditional statement that filters an encoding specific case.
       * Below if statement is just for my case.
       */
      if (req.path === "/some/path/to/treat/differently") {
        req.body = urlencode.parse(decoded,{ charset: "euc-kr" })
      }
      else {
        req.body = qs.parse(decoded);
      }
    }
    next();
  }
);

相关问答

错误1:Request method ‘DELETE‘ not supported 错误还原:...
错误1:启动docker镜像时报错:Error response from daemon:...
错误1:private field ‘xxx‘ is never assigned 按Alt...
报错如下,通过源不能下载,最后警告pip需升级版本 Requirem...