我正在尝试发送一个POST请求到一个使用SHIFT-JIS解码的服务器。这个字符串サービス在SHIFT-JIS中被解码后正在被翻译成繧オ繝シ繝薙せ。似乎无论何时发送请求,请求都将始终以UTF-8编码。我使用nodejs发布请求。问题是我如何发送shift-jis编码中的字符?这看起来很简单,但我就是不知道怎么做。
监听服务器
var iconv = require('iconv-lite');
const http = require('http');
http.createServer((request, response) =>
{
const
{
headers,
method,
url
} = request;
let body = [];
request.on('error', (err) =>
{
console.error(err);
}
).on('data', (chunk) =>
{
body.push(chunk);
}
).on('end', () =>
{
body = Buffer.concat(body).toString();
// BEGINNING OF NEW STUFF
body = iconv.decode(Buffer.from(body), 'shift_jis');
response.on('error', (err) =>
{
console.error(err);
}
);
response.statusCode = 200;
response.setHeader('Content-Type', 'application/json');
// Note: the 2 lines above could be replaced with this next one:
// response.writeHead(200, {'Content-Type': 'application/json'})
const responseBody =
{
headers,
method,
url,
body
};
response.write(JSON.stringify(responseBody));
console.log(body);
console.log(responseBody);
response.end();
// Note: the 2 lines above could be replaced with this next one:
// response.end(JSON.stringify(responseBody))
// END OF NEW STUFF
}
);
}
).listen(8000);请求
var request = require('request');
request({
url: 'http://localhost:8000',
headers: { 'Content-Type': 'application/x-www-form-urlencoded; charset=shift_jis' },
method: 'POST',
body: 'サービス'
}, function(error, response, body){
if(error) {
console.log(error);
} else {
console.log(response.statusCode, body);
}
});编辑:事实证明,我们用于HTTPS POST的axios模块将在发送请求之前将有效负载编码为UTF-8。我们克隆了axios模块,并将其修改为使用SHIFT-JIS进行编码。
发布于 2020-12-09 22:38:57
如果要发送Shift-JIS编码的字符串,则必须将目标字符串(在内部以UTF-16表示)转换为Shift-JIS,然后再将其添加到请求正文中。
标准TextEncoder仅支持UTF8编码,无法处理Shift-JIS编码。因此,您必须使用诸如encoding.js或text-encoding之类的附加模块来实现此目的。
https://stackoverflow.com/questions/65105712
复制相似问题