当正文充满缓冲区时,不会从响应正文中剥离 BOM
request({
url: url,
json: true,
strictSSL: false,
}, (error, response, data) => {
if (error) {
throw error;
}
if (response.statusCode === 200) {
// data is string instead of json deserialized object
}
})
BOM 字符剥离和 json 响应反序列化
JSON.parse 失败并返回一个字符串
if (bufferLength) {
debug('has body', self.uri.href, bufferLength)
response.body = Buffer.concat(buffers, bufferLength)
if (self.encoding !== null) {
response.body = response.body.toString(self.encoding)
}
// `buffer` is defined in the parent scope and used in a closure it exists for the life of the Request.
// This can lead to leaky behavior if the user retains a reference to the request object.
buffers = []
bufferLength = 0
} else if (strings.length) {
// The UTF8 BOM [0xEF,0xBB,0xBF] is converted to [0xFE,0xFF] in the JS UTC16/UCS2 representation.
// Strip this value out when the encoding is set to 'utf8', as upstream consumers won't expect it and it breaks JSON.parse().
if (self.encoding === 'utf8' && strings[0].length > 0 && strings[0][0] === '\uFEFF') {
strings[0] = strings[0].substring(1)
}
response.body = strings.join('')
}
正如我们所看到的,当使用字符串而不是缓冲区时,BOM 字符被剥离
提取 else if (strings.length) 之外的代码以始终清理响应正文。
从基于 swashbuckle 的公司自定义 swagger 读取 json 响应
| 软件| 版本
| ---------------- | -------
| 请求 | 2.83.0
| 节点 | 9.3.0
| npm | 5.5.1
| 操作系统 | 视窗 10
如果我们在请求的选项中设置 encoding: 'utf8',则响应被解析
此问题已自动标记为过时,因为它最近没有活动。 如果没有进一步的活动发生,它将被关闭。 感谢你的贡献。
我也看到了这个问题 - 感谢您发布解决方法 - 如果图书馆处理这个问题会很好。
最有用的评论
如果我们在请求的选项中设置 encoding: 'utf8',则响应被解析