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

Aberta Para iniciantes
#60 0 comentários 0 reações 0 responsáveis Ver no GitHub

Ninguém assumiu esta issue ainda.

Avaliação

Dificuldade
2/5
Tempo estimado
1-3 horas
Facilidade para iniciantes
82/100
Tipo de issue
Bug
Clareza
Claramente especificada
Status de atividade
Ativa
Stack de tecnologia
javascript, node.js

Direção de pesquisa

A issue aponta para _handleResponse em lib/httpClient.js (linhas 105–114). Leia como a função decide analisar os corpos das respostas e, em seguida, confira os testes existentes para httpClient.head(url) e httpClient(url, {method: 'HEAD'}). O trabalho estará concluído quando ambas as formas forem resolvidas com sucesso, com response.data undefined para um tipo de conteúdo JSON.

Escrita pelo modelo de indexação a partir do texto da issue.

Descrição

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.

Linguagem predominante
JavaScript
Estrelas
2
Forks
8
Métricas de merge de PRs
Nenhum PR com merge em 30d

Preparar o ambiente

Este projeto não oferece contêiner de desenvolvimento, Dockerfile nem guia de contribuição, então a configuração fica por sua conta: comece pelo README e veja nosso guia da primeira contribuição para os passos gerais.

Primeiros passos

  1. Leia a issue inteira e depois o guia de contribuição do projeto.
  2. Comente na issue dizendo que vai assumir — evita que duas pessoas façam o mesmo trabalho.
  3. Faça um fork do repositório e trabalhe em uma branch.
  4. Abra um pull request que referencie o número da issue.

Mais de digitalbazaar/http-client

Todas as issues de digitalbazaar/http-client

Issues semelhantes

Mais issues de JavaScript

Receba novas issues na sua caixa de entrada

Um resumo curto de issues do GitHub para quem está começando.