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

未关闭 适合新手
#60 0 条评论 0 个 reaction 已指派 0 人 在 GitHub 查看

还没有人认领这个 Issue。

评估

难度
2/5
预计耗时
1-3 小时
新手友好度
82/100
Issue 类型
缺陷
描述清晰度
描述清楚
活跃度
活跃

调研方向

Issue 指向 lib/httpClient.js 中的 _handleResponse(第 105–114 行)。阅读它如何选择解析响应体,然后检查 httpClient.head(url) 和 httpClient(url, {method: 'HEAD'}) 的现有测试。当两种形式都能成功解析,且 JSON 内容类型下 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. Fork 仓库,在一个分支上完成修改。
  4. 提交 Pull Request,并在描述里引用这个 Issue 编号。

digitalbazaar/http-client 的其他 Issue

查看 digitalbazaar/http-client 的全部 Issue

相似的 Issue

更多 JavaScript Issue

把新 issue 发到你的邮箱

精选适合新手参与的 GitHub issue 摘要。