Return JSON ISO-8859-1 响应 NodeJS/Express

Return JSON response in ISO-8859-1 with NodeJS/Express

我用 Node 和 Express 构建了一个 API,其中 return 有一些 JSON。 JSON 数据将由 Web 应用程序读取。遗憾的是,此应用程序仅接受 ISO-8859-1 编码 JSON,这已被证明有点困难。

我无法使用正确的编码 return JSON 即使我已经尝试了 Express 文档中的方法以及谷歌搜索问题的所有提示。

Express 文档说使用 "res.set()" 或 "res.type()",但其中 none 对我有用。注释行是我尝试过的所有变体(使用 Mongoose):

MyModel.find()
.sort([['name', 'ascending']])
.exec((err, result) => {
  if (err) { return next(err) }

  // res.set('Content-Type', 'application/json; charset=iso-8859-1')
  // res.set('Content-Type', 'application/json; charset=ansi')
  // res.set('Content-Type', 'application/json; charset=windows-1252')
  // res.type('application/json; charset=iso-8859-1')
  // res.type('application/json; charset=ansi')
  // res.type('application/json; charset=windows-1252')

  // res.send(result)
  res.json(result)
})

None这些对响应有什么影响,它总是变成"Content-Type: application/json; charset=utf-8"。

由于 JSON 应该(?)以 utf-8 编码,是否可以在 Express 中使用任何其他编码?

如果您查看 Express 源代码中的 lib/response.js 文件(在您的 node_modules 文件夹或 https://github.com/expressjs/express/blob/master/lib/response.js 中),您会看到 res.json 占用了您的result,在JavaScriptString中生成相应的JSON表示,然后将该字符串传递给res.send

你的问题的原因是当 res.send (在同一个源文件中)被赋予 String 参数时,它将字符串编码为 UTF8 并强制 charsetutf-8.

的回应

您可以通过不使用 res.json 来解决这个问题。而是自己构建编码响应。首先使用您现有的代码设置 Content-Type header:

    res.set('Content-Type', 'application/json; charset=iso-8859-1')

之后,手动生成JSON字符串:

    jsonString = JSON.stringify(result);

然后将该字符串作为 ISO-8859-1 编码为 Buffer:

    jsonBuffer = Buffer.from(jsonString, 'latin1');

最后,将该缓冲区传递给 res.send:

    res.send(jsonBuffer)

因为不再使用 String 参数调用 res.send,它应该跳过强制 charset=utf-8 的步骤,并且应该发送带有 charset 的响应您指定的值。