node-fetch的Promise响应headers指定字段取值返回undefined原因排查
问题根源
node-fetch 返回的响应头 theResponse.headers 并不是普通 JavaScript 对象,而是实现了 Fetch 标准 Headers 接口的类实例,不支持直接通过方括号 [] 读取字段值,必须调用实例提供的专用方法取值。
正确写法
- 单次读取指定header字段,调用
get()方法:
fetch(new URL("https://www.stackoverflow.com")).then(theResponse =>{ console.log("This prints OK: "); console.log(theResponse.headers); console.log("现在可以正常读取到值:"); console.log(theResponse.headers.get("content-encoding")); // 输出 gzip return theResponse; })
- 如果需要把所有header转为普通对象方便批量操作,可以用
entries()迭代器转换:
const headersObj = Object.fromEntries(theResponse.headers.entries()); console.log(headersObj["content-encoding"]); // 输出 gzip
为什么打印headers能看到对应字段
node-fetch 为了方便调试,对Headers实例的控制台输出逻辑做了特殊处理,打印时会把内部存储的所有header字段格式化为普通对象的结构展示,但这并不代表它本身就是普通对象,直接通过属性名读取的操作是不生效的。
内容的提问来源于stack exchange,提问作者garson
相关产品推荐
相关产品推荐

