使用 fetch() 获取响应文本需调用响应对象的 .text() 方法,它返回 Promise,须用 await 或 .then() 处理;注意检查 response.ok 避免 HTTP 错误状态被忽略;.text() 仅能调用一次,且不可与其他读取方法混用。

使用 fetch() 获取响应的文本内容,核心是调用响应对象的 .text() 方法,它返回一个 Promise,解析成功后得到字符串。
基本用法:调用 .text() 并等待结果
.text() 是响应对象(Response)的内置方法,必须在 fetch() 返回的 Promise 解析为响应后调用。它本身也返回 Promise,所以通常需要 await 或 .then() 处理。
- 使用
async/await(推荐):
async function getText() {
try {
const response = await fetch('/api/data.txt');
const text = await response.text(); // ✅ 关键步骤
console.log(text);
} catch (error) {
console.error('请求失败:', error);
}
}
- 使用
.then()链式调用:
fetch('/api/data.txt')
.then(response => response.text()) // ✅ 先转成文本 Promise
.then(text => console.log(text))
.catch(error => console.error('错误:', error));
注意响应状态,避免静默失败
fetch() 只在网络错误时 reject,HTTP 错误状态(如 404、500)仍会进入 then。因此建议检查 response.ok 或 response.status。
-
response.ok为true表示状态码在 200–299 范围内 - 未检查时,404 响应仍会执行
.text(),返回的是错误页面的 HTML 文本,容易误判
const response = await fetch('/api/data.txt');
if (!response.ok) {
throw new Error(`HTTP 错误: ${response.status}`);
}
const text = await response.text();
与其他响应方法的区别
.text() 专用于获取纯文本;根据实际内容类型,可选其他方法:
立即学习“Java免费学习笔记(深入)”;
-
.json():自动解析 JSON,失败时抛错(适合 API 返回 JSON) -
.blob():获取二进制数据(如图片、文件下载) -
.arrayBuffer():获取底层字节数组(用于高级处理)
⚠️ 同一个响应对象只能调用一次 .text()(或其它读取方法),重复调用会返回空字符串或报错 —— 因为响应体是“一次性流”。


















