[英]Convert character set from none-standard one to UTF-8
有一個帶有<meta charset="EUC-KR">
的頁面,比如 address-search.foo.com 搜索地址並將其發送到指定的 url 通過提交 ZFC35FDC70D5FC69D269883A82ZC 的方法如下所示。
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();
}
);
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.