为何JSON.parse未报错却忽略数据?npm包接口readme字段异常排查
Why is the
readme field empty when parsing npm registry JSON with fetch? Great question! Let me break down exactly what's going on here:
The Root Cause
The npm registry API serves different versions of package metadata based on the Accept header included in your request:
- When you load the URL directly in your browser, your browser sends an
Acceptheader that includes values liketext/htmlorapplication/json. The registry responds with the full package metadata, including the completereadmecontent you see. - When you use a default
fetch()call, the browser sends a broaderAcceptheader (typically*/*). The npm registry interprets this as a request for the minified, install-focused version of the metadata—this is the format npm uses internally when installing packages, so non-essential fields likereadmeare emptied to reduce payload size.
How to Fix It
To retrieve the full metadata (including the complete readme), explicitly set the Accept header to application/json in your fetch request:
fetch('http://registry.npmjs.org/core-js', { headers: { 'Accept': 'application/json' } }) .then(response => response.json()) .then(data => console.log(data.readme)); // Now you'll see the full README content!
Quick Way to Verify
You can confirm this behavior using your browser's dev tools:
- Load the URL directly and check the
Acceptrequest header in the Network tab—you'll see the fullreadmein the response. - Run your original
fetchcode, inspect the request headers, and notice the response has an emptyreadmefield. - Run the modified
fetchcode with the explicitAcceptheader, and you'll see the fullreadmeloads correctly.
内容的提问来源于stack exchange,提问作者Juan Picado
相关产品推荐
相关产品推荐

