【问题标题】:Return JSON response in ISO-8859-1 with NodeJS/Express使用 NodeJS/Express 在 ISO-8859-1 中返回 JSON 响应
【发布时间】:2019-08-11 08:39:52
【问题描述】:

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

即使我尝试了 Express 文档中的方法以及谷歌搜索问题的所有提示,我也无法设法返回具有正确编码的 JSON。

Express 文档说要使用“res.set()”或“res.type()”,但这些都不适合我。注释行是我尝试过的所有变体(使用 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)
})

这些都对响应没有任何影响,它总是变成“Content-Type: application/json; charset=utf-8”。

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

【问题讨论】:

    标签: node.js json express utf-8 iso-8859-1


    【解决方案1】:

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

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

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

        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 值发送响应。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2015-10-11
      • 1970-01-01
      • 1970-01-01
      • 2015-07-29
      • 2018-07-25
      • 2011-06-10
      • 1970-01-01
      相关资源
      最近更新 更多