概述
response.type 是 Fetch API 中的一个重要属性,用于获取响应的内容类型。这个属性对于判断服务器返回的内容类型非常有用,可以帮助开发者更有效地处理数据。
类型值
response.type 返回一个字符串,表示响应的类型。以下是可能的类型值:
basic
当响应来自同源资源时,返回 basic。这意味着请求是同一个域内的请求,或者通过 CORS (Cross-Origin Resource Sharing) 请求成功,并且服务器允许跨域访问。
fetch('https://www.example.com/same-origin')
.then(response => {
console.log(response.type); // "basic"
});cors
当响应来自不同源的资源,并且通过 CORS 成功获取时,返回 cors。这种情况下,响应的某些部分(如头部信息)可能被限制。
fetch('https://api.example.com/data', {
mode: 'cors'
})
.then(response => {
console.log(response.type); // "cors"
});error
当请求过程中发生错误时,返回 error。这通常意味着网络问题或其他类型的错误。
fetch('https://nonexistent-domain.com')
.then(response => {
console.log(response.type); // "error"
})
.catch(error => {
console.error('Error:', error);
});opaque
当请求的目标是一个跨域资源,并且该资源不允许跨域访问时,返回 opaque。在这种情况下,你无法从响应对象中获取任何信息,除了知道这是一个失败的请求。
fetch('https://blocked-by-csp.com')
.then(response => {
console.log(response.type); // "opaque"
});opaqueredirect
当请求是通过 redirect: 'manual' 或 redirect: 'follow' 选项进行重定向时,如果目标资源是跨域资源且不允许跨域访问,则返回 opaqueredirect。
// www.javascriptcn.com code example
fetch('https://example.com/redirect-to-blocked-url', {
redirect: 'manual'
})
.then(response => {
if (response.status === 302) {
fetch(response.headers.get('Location'), {
credentials: 'include',
mode: 'no-cors'
}).then(r => {
console.log(r.type); // "opaqueredirect"
});
}
});实际应用场景
了解和使用 response.type 对于前端开发人员来说非常重要。例如,在处理用户认证时,你可能需要根据响应类型来决定下一步的操作:
- 如果响应类型是
basic或cors,你可以解析响应体来获取用户信息。 - 如果响应类型是
error,你需要显示错误信息给用户。 - 如果响应类型是
opaque或opaqueredirect,你需要告知用户当前请求由于跨域限制而无法完成。
// www.javascriptcn.com code example
fetch('/login', {
method: 'POST',
headers: {
'Content-Type': 'application/json'
},
body: JSON.stringify({ username: 'user', password: 'pass' })
})
.then(response => {
switch (response.type) {
case 'basic':
case 'cors':
return response.json();
case 'error':
throw new Error('Network response was not ok.');
default:
throw new Error('Unexpected response type.');
}
})
.then(data => {
console.log('Login successful:', data);
})
.catch(error => {
console.error('Login failed:', error);
});总结
response.type 提供了关于响应类型的重要信息,这对于处理不同类型的网络请求至关重要。理解这些类型以及它们的含义,可以帮助开发者更好地控制和处理请求的结果,从而构建更健壮的应用程序。