[英]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.