HEAD response with a JSON content-type throws "Unexpected end of JSON input"

Abierto Apto para principiantes
#60 0 comentarios 0 reacciones 0 asignados Ver en GitHub

Nadie ha tomado este issue todavía.

Evaluación

Dificultad
2/5
Tiempo estimado
1-3 horas
Aptitud para principiantes
82/100
Tipo de issue
Error
Claridad
Bien especificado
Estado de actividad
Activo
Stack tecnológico
javascript, node.js

Línea de trabajo

El issue señala _handleResponse en lib/httpClient.js (líneas 105–114). Lee cómo decide analizar los cuerpos de las respuestas y luego revisa las pruebas existentes para httpClient.head(url) y httpClient(url, {method: 'HEAD'}). Se considera terminado cuando ambas formas se resuelvan correctamente con response.data undefined para un tipo de contenido JSON.

Escrito por el modelo de indexación a partir del texto del issue.

Descripción

A HEAD request to an endpoint that serves JSON rejects with SyntaxError: Unexpected end of JSON input, even though the request succeeded.

A HEAD response carries the same headers as the GET, including Content-Type: application/json, but has no body. _handleResponse decides whether to parse from the content-type alone, so it calls response.json() on the empty body:

https://github.com/digitalbazaar/http-client/blob/main/lib/httpClient.js#L105-L114

Reproduction

Seen with 4.4.0 on Node 24.

import {createServer} from 'node:http';
import {httpClient} from '@digitalbazaar/http-client';

const server = createServer((req, res) => {
  const body = JSON.stringify({ok: true});
  res.writeHead(200, {
    'content-type': 'application/json',
    'content-length': Buffer.byteLength(body)
  });
  // a HEAD response carries the GET's headers and no body
  res.end(req.method === 'HEAD' ? undefined : body);
});
await new Promise(resolve => server.listen(0, resolve));
const url = `http://localhost:${server.address().port}/`;

console.log('GET ', (await httpClient.get(url)).data);
try {
  console.log('HEAD', (await httpClient.head(url)).status);
} catch(e) {
  console.log('HEAD threw:', e.name, '-', e.message);
}
server.close();

Output:

GET  { ok: true }
HEAD threw: SyntaxError - Unexpected end of JSON input
Expected

The HEAD resolves with the response, and response.data is undefined.

Workaround

Passing parseBody: false avoids it. That only helps a caller that controls the options, which is not the case when the request is made through a wrapper such as ezcap's ZcapClient.request().

Suggested fix

Skip the body parse when the request method is HEAD, both for httpClient.head(url) and for the direct httpClient(url, {method: 'HEAD'}) form. Happy to send a PR.

Lenguaje dominante
JavaScript
Estrellas
2
Forks
8
Métricas de merge de PR
Sin PR fusionados en 30 d

Preparar el entorno

Este proyecto no incluye contenedor de desarrollo, Dockerfile ni guía de contribución, así que la configuración corre por tu cuenta: empieza por su README y consulta nuestra guía para la primera contribución para los pasos generales.

Primeros pasos

  1. Lee el issue completo y luego la guía de contribución del proyecto.
  2. Comenta en el issue que vas a ocuparte — evita que dos personas hagan lo mismo.
  3. Haz un fork del repositorio y trabaja en una rama.
  4. Abre un pull request que haga referencia al número del issue.

Más de digitalbazaar/http-client

Todos los issues de digitalbazaar/http-client

Issues similares

Más issues de JavaScript

Recibe los nuevos issues en tu correo

Un resumen breve de issues de GitHub para principiantes.