我有一个简单的应用程序,它使用 jquery ajax 请求将表单数据发送到 Node 服务器, Node 服务器又使用 Node js 的请求模块提交给第三方 api。

我遇到的问题是重音(和其他类似)字符在到达第三方服务器时没有正确编码。例如 é 被记录为 é

我相当确定这与 Request 的设置有关,因为当我绕过 ajax 调用时我得到了相同的结果。

以下是我正在使用的设置:

html:

<meta http-equiv="Content-type" content="text/html; charset=utf-8" />

jquery ajax设置:
type        : 'POST',
url         : '/api',
data        : formData, // A json object
dataType    : 'json',
ContentType : 'text/html; charset=utf-8'

Node 中的请求模块设置(ajax post 和请求发送之间的表单数据没有发生任何变化):
request.post({
    url: "https://testurl.com/api/",
    form: formData,
    headers: {'Content-Type': 'application/json; charset=utf-8'}
} ...

我已经阅读了各种 SO 解决方案,但没有成功,因此非常感谢任何建议。

最佳答案

在研究了字符编码后,我发现问题与各种字符的多字节编码有关(快速谷歌会找到一些关于该主题的好帖子)。

我认为 Request 没有自动处理这个问题很奇怪,所以我尝试了 Request 语法并设法解决了这个问题。这是我修改后的有效代码:

request(
    {
        url: 'https://testurl.com/api/',
        method: 'POST',
        json: true,
        headers: {
            'content-type': 'application/json'
        },
        body: formData
    },
    function (error, response, body) {
        ...
    }
);

10-08 03:11