Fetch API 的 Response.headers 可读取响应头(如 Content-Type),但跨域时仅暴露默认头,自定义头需服务端通过 Access-Control-Expose-Headers 显式声明;Content-Type 属于默认暴露头,可用 get()、has() 或 entries() 访问。

Fetch API 返回的 Response 对象提供了 headers 属性,它是一个 Headers 对象,支持读取响应头(包括 Content-Type),但需注意跨域限制和 CORS 配置。
获取响应头的基本方法
Response.headers 是一个只读的 Headers 对象,不能直接打印或遍历全部字段(尤其在跨域请求中受限制),但可通过以下方式访问特定头:
- 使用
response.headers.get('Content-Type')获取指定头的值(区分大小写不敏感) - 用
response.headers.has('Content-Type')判断头是否存在 - 通过
response.headers.entries()或response.headers.keys()遍历(仅限同源或服务端明确暴露的头)
Content-Type 的常见获取方式
Content-Type 是最常读取的响应头之一,通常用于判断返回数据类型(如 application/json、text/html、application/pdf):
在 Java 中初始化和管理阿里云 SDK客户端。包括单例模式、线程安全、endpoint 与 region 配置、VPC 终端节点、同步与异步等。
-
const contentType = response.headers.get('content-type');—— 推荐写法,不区分大小写 - 返回值可能是完整字符串,例如
"application/json; charset=utf-8",可用contentType?.includes('json')粗略判断 - 若需精确解析 MIME 类型,可配合正则或
new Headers().get('content-type')辅助提取主类型
跨域请求下获取响应头的限制
浏览器出于安全考虑,默认只暴露部分“简单响应头”(Cache-Control、Content-Language、Content-Type、Expires、Last-Modified、Pragma)。其他头(如 X-Request-ID)必须由服务端显式声明:
立即学习“Java免费学习笔记(深入)”;
- 服务端需在响应中添加
Access-Control-Expose-Headers: X-Request-ID, Content-Length - 否则调用
response.headers.get('X-Request-ID')将返回null,即使服务端确实设置了该头 -
Content-Type属于默认暴露头,一般无需额外配置即可读取
完整示例:请求并检查响应头
注意:fetch 不会自动抛出 HTTP 错误状态(如 404/500),需手动检查 response.ok 或 response.status。
fetch('/api/data')
.then(response => {
if (!response.ok) throw new Error(`HTTP ${response.status}`);
const contentType = response.headers.get('content-type');
console.log('Content-Type:', contentType); // e.g. "application/json; charset=utf-8"
// 检查是否为 JSON 响应
if (contentType && contentType.includes('application/json')) {
return response.json();
}
// 否则按文本处理
return response.text();
})
.then(data => console.log(data))
.catch(err => console.error(err));

















