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

オープン 初心者向け
#60 コメント 0 件 リアクション 0 件 担当者 0 名 GitHub で見る

まだ誰も着手していません。

評価

難易度
2/5
見積もり時間
1〜3時間
初心者へのやさしさ
82/100
issue の種類
バグ
明瞭さ
明確に書かれている
活発さ
活発
技術スタック
javascript, node.js

調査の方向性

issue では lib/httpClient.js の _handleResponse(105–114 行)が示されています。レスポンス本文を解析するかどうかの決定方法を読み、httpClient.head(url) と httpClient(url, {method: 'HEAD'}) の既存テストを確認してください。JSON の Content-Type の場合に、どちらの形式も response.data が undefined の状態で正常に解決されれば完了です。

索引モデルが issue の本文から書いたものです。

説明

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.

主要言語
JavaScript
スター
2
フォーク
8
PR マージ指標
30日以内にマージされた PR はありません

環境構築

このプロジェクトには開発コンテナ、Dockerfile、コントリビューションガイドがありません。まず README を読み、一般的な手順ははじめてのコントリビューションガイドを参照してください。

はじめの一歩

  1. issue を最後まで読み、次にプロジェクトのコントリビューションガイドを読みます。
  2. 着手することを issue にコメントします — 二人が同じ作業をするのを防げます。
  3. リポジトリをフォークし、ブランチを切って変更します。
  4. issue 番号を参照したプルリクエストを送ります。

digitalbazaar/http-client のほかの issue

digitalbazaar/http-client の issue をすべて見る

似ている issue

JavaScript の issue をもっと見る

新しい issue をメールで受け取る

初心者向けの GitHub issue を短くまとめたダイジェスト。