ボディがバッファで満たされたときに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'を設定すると、レスポンスが解析されます