在 TypeScript 中,response 通常指的是 HTTP 响应对象。这个对象包含了服务器返回的所有信息,包括状态码、头部信息和响应体等。以下是对 response 对象的一些常见操作和属性的解析:
-
响应状态:
response.status: number; // HTTP状态码(如200, 404等) response.ok: boolean; // 如果状态码在200-299之间,则为true response.statusText: string; // 状态描述文本 -
响应头:
response.headers: Headers; // 响应头对象 // 获取特定头部信息 response.headers.get('Content-Type'): string | null; -
响应体: 根据响应的内容类型,可以使用不同的方法解析响应体:
// 解析为JSON response.json(): Promise<any>; // 解析为文本 response.text(): Promise<string>; // 解析为Blob对象(用于二进制数据) response.blob(): Promise<Blob>; // 解析为ArrayBuffer response.arrayBuffer(): Promise<ArrayBuffer>; // 解析为FormData对象 response.formData(): Promise<FormData>; -
其他属性:
response.url: string; // 响应的完整URL response.type: ResponseType; // 响应的类型(如"basic", "cors") -
示例使用:
async function fetchData(url: string) { try { const response = await fetch(url); if (!response.ok) { throw new Error(`HTTP error! status: ${response.status}`); } const contentType = response.headers.get('content-type'); if (contentType && contentType.includes('application/json')) { const data = await response.json(); console.log(data); } else { const text = await response.text(); console.log(text); } } catch (error) { console.error('Fetch error:', error); } } -
使用 Axios 库时的 response 对象:
如果使用 Axios,
response对象的结构略有不同:interface AxiosResponse<T = any> { data: T; // 响应体数据 status: number; // HTTP状态码 statusText: string; // 状态描述文本 headers: any; // 响应头 config: AxiosRequestConfig; // 请求配置 request?: any; // 请求对象 }Axios 示例:
import axios from 'axios'; async function fetchData(url: string) { try { const response = await axios.get(url); console.log(response.data); // 已经解析好的数据 console.log(response.status); console.log(response.headers); } catch (error) { console.error('Axios error:', error); } }
在 TypeScript 中处理 response 对象时,了解这些属性和方法可以帮助你更有效地处理 HTTP 响应,进行错误处理,并正确解析返回的数据。