You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在Express中处理重音字符?POST请求重音字符异常求助

Fixing Accent Character Issues in Your POST Request

Let’s walk through the common pitfalls that might be causing your accent character problems, and fix them based on your code snippet:

1. Fix the Content-Length Calculation (Critical!)

The biggest red flag in your code is how you’re calculating Content-Length. Using bodyString.len (I assume that’s a typo for bodyString.length) gives you the number of characters, not the number of bytes in the UTF-8 encoded string. Accented characters like é, ñ, or ü take up 2-4 bytes each, so this mismatch will cause the receiving server to truncate or misparse the request body—directly leading to garbled accents.

Replace that line with:

'Content-Length': Buffer.byteLength(bodyString, 'utf8')

This correctly calculates the byte count of your UTF-8 encoded JSON string.

2. Ensure Request Body Parsing Uses UTF-8

If you’re using a middleware like body-parser to parse req.body, double-check that it’s configured to use UTF-8. Most middlewares default to this, but it’s worth explicitly setting it to eliminate any ambiguity:

// If using body-parser for JSON
const bodyParser = require('body-parser');
app.use(bodyParser.json({ charset: 'utf-8' }));

If you’re manually parsing the incoming request body (without middleware), make sure you read it using UTF-8 encoding:

req.setEncoding('utf8');
let rawBody = '';
req.on('data', chunk => rawBody += chunk);
req.on('end', () => {
  req.body = JSON.parse(rawBody);
  // Proceed with your POST request logic
});

3. Properly Encode the Request Body as UTF-8 Buffer

Since you’ve set encoding: null in your options, the request expects a Buffer instead of a string. Converting your JSON string to a UTF-8 Buffer ensures the bytes sent over the wire are correctly encoded for accents:

var bodyString = JSON.stringify(req.body);
var bodyBuffer = Buffer.from(bodyString, 'utf8'); // Explicit UTF-8 encoding
var options = {
  host: XXXXX,
  port: XXX,
  path: url,
  method: 'POST',
  encoding: null,
  rejectUnauthorized: false,
  headers: {
    "OAM_SFID": header.sfid,
    "X-FORWARDED-SERVER": header.server,
    "OAM_TIENE_PERFIL": header.loginType,
    "OAM_REMOTE_USER": header.user,
    "Content-Type": "application/json;charset=UTF-8",
    'Content-Length': bodyBuffer.length // Use buffer's byte length
  }
};
// Then write the buffer to the request
const req = https.request(options, res => { /* ... */ });
req.write(bodyBuffer);
req.end();

4. Why Iconv Might Have Failed

If you tried using iconv and it didn’t help, it’s likely because you were converting in the wrong direction. Iconv is only useful if your source data is in a non-UTF-8 encoding (like ISO-8859-1) that needs to be converted to UTF-8. If req.body is already in UTF-8 (which it should be if parsed correctly), running it through iconv will corrupt the characters instead of fixing them.

Only use iconv if you know the incoming request is in a different encoding, for example:

const iconv = require('iconv-lite');
// If raw incoming body is in ISO-8859-1
const utf8Body = iconv.decode(Buffer.from(rawBody, 'binary'), 'ISO-8859-1');
req.body = JSON.parse(utf8Body);

Quick Test to Verify

Send a test request with a known accented string (e.g., {"name": "José García"}) and:

  • Log bodyBuffer to check if the bytes match the expected UTF-8 encoding (for é, it should be 0xC3 0xA9)
  • Check the receiving server’s logs to confirm it’s parsing the JSON correctly

内容的提问来源于stack exchange,提问作者EspeonDevelop

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.25 06:27:05