Request: JSON.parse falla debido al carácter BOM

Creado en 5 ene. 2018  ·  3Comentarios  ·  Fuente: request/request

Resumen

La lista de materiales no se quitó del cuerpo de respuesta cuando el cuerpo se llenó con búfer

El ejemplo más sencillo de reproducir

    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 
        }
    })

Comportamiento esperado

BOM char despojado y respuesta json deserializada

Comportamiento actual

JSON.parse falla y se devuelve una cadena

Solución posible

    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('')
    }

Como podemos ver, el carácter BOM se elimina cuando se utilizan cadenas en lugar de búfer
Extraiga el código fuera del else if (strings.length) para limpiar siempre el cuerpo de la respuesta.

Contexto

Lectura de la respuesta de json de una fanfarronería personalizada de la empresa basada en bravuconería

Tu entorno

| software | versión
| ---------------- | -------
| solicitud | 2.83.0
| nodo | 9.3.0
| npm | 5.5.1
| Sistema operativo | Windows 10

stale

Comentario más útil

Si configuramos encoding: 'utf8' en las opciones de la solicitud, la respuesta se analiza

Todos 3 comentarios

Si configuramos encoding: 'utf8' en las opciones de la solicitud, la respuesta se analiza

Este problema se ha marcado automáticamente como obsoleto porque no ha tenido actividad reciente. Se cerrará si no se produce más actividad. Gracias por sus aportaciones.

También estoy viendo este problema, gracias por publicar la solución alternativa, sin embargo, sería bueno que la biblioteca manejara esto.

¿Fue útil esta página
0 / 5 - 0 calificaciones