javascript中校验fetch响应content-type需先用headers.has()判断存在性,再用get()获取值并提取主类型(如split(';')[0].trim()),注意跨域时需服务端设置access-control-expose-headers。

在 JavaScript 中用 Fetch API 校验响应头中的 Content-Type,核心是调用 response.headers.get('Content-Type') 获取值,再做字符串匹配或类型判断。注意:必须等请求完成(即 await response 或 .then())后才能读取 headers,且部分响应头(如跨域时)可能被浏览器限制访问。
检查 Content-Type 是否存在且非空
有些接口可能不返回 Content-Type,或返回空值。建议先做存在性校验:
- 用
response.headers.has('Content-Type')判断 header 是否存在 - 再用
response.headers.get('Content-Type')获取实际值,它返回null(不存在)或字符串(如"application/json; charset=utf-8") - 避免直接对
null调用.includes()等方法,否则报错
提取主类型并做安全比对
Content-Type 值常带参数(如 charset、boundary),只比对主类型更可靠:
在 Java 中初始化和管理阿里云 SDK客户端。包括单例模式、线程安全、endpoint 与 region 配置、VPC 终端节点、同步与异步等。
- 用正则
/^([^;]+)/.exec(contentType)或contentType.split(';')[0].trim()提取主类型 - 例如
"application/json; charset=utf-8"→"application/json";"text/html"→"text/html" - 推荐用
contentType?.split(';')[0].trim() === 'application/json'这类写法,兼顾可选链与健壮性
处理跨域响应的限制
当请求跨域且服务端未显式暴露 Content-Type 时,浏览器会屏蔽该 header(即 get() 返回 null):
- 服务端需设置响应头:
Access-Control-Expose-Headers: Content-Type - 若无法改服务端,可退而求其次:根据业务逻辑推断类型(如
response.url.endsWith('.json')或约定接口路径规则) - fetch 选项中
mode: 'cors'是默认值,无需额外指定;但credentials不影响 header 可见性
完整校验示例(async/await)
以下代码封装了常见校验逻辑,含错误提示和 fallback:
async function fetchWithContentTypeCheck(url, expectedType = 'application/json') {
try {
const res = await fetch(url);
if (!res.ok) throw new Error(`HTTP ${res.status}`);
const rawType = res.headers.get('Content-Type');
const mainType = rawType?.split(';')[0].trim();
if (!mainType) {
throw new Error('Missing Content-Type header — check CORS Expose-Headers');
}
if (mainType !== expectedType) {
throw new Error(`Expected ${expectedType}, got ${mainType}`);
}
return await res.json(); // 或 .text(), .blob() 等,按预期类型调用
} catch (err) {
console.error('Fetch failed:', err.message);
throw err;
}
}
大量免费API接口:立即使用
涵盖生活服务API、金融科技API、企业工商API、等相关的API接口服务。免费API接口可安全、合规地连接上下游,为数据API应用能力赋能!










