将字符集从 none-standard one 转换为 UTF-8

Convert character set from none-standard one to UTF-8

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

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

并且 ExpressJs 在 my-service.foo.com 运行 中有一个 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 (������)'
}

我尝试使用 iconv-lite 模块转换 req.body.address 的编码,但它无法像在 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();
  }
);