在现代ref="/tag/88/" style="color:#8B0506;font-weight:bold;">网页开发中,经常需要从服务器获取数据,比如加载用户信息、提交表单结果或动态刷新商品列表。过去大家常用 XMLHttpRequest,现在有了更简洁的方式——fetch。它基于 Promise,语法清晰,用起来顺手。
fetch 的基本用法
调用 fetch 只需传入一个 URL,它会返回一个 Promise。比如想从接口获取一篇博客文章:
fetch('/api/posts/1')
.then(response => response.json())
.then(data => console.log(data));
这段代码向 /api/posts/1 发起 GET 请求,拿到响应后通过 .json() 方法解析成 JavaScript 对象,最后打印出来。整个过程没有回调地狱,逻辑一目了然。
处理不同类型的响应
除了 JSON,fetch 也能处理文本、图片等资源。如果只是想读取页面的原始文本内容:
fetch('/readme.txt')
.then(response => response.text())
.then(text => console.log(text));
要是要下载一张图片并显示在页面上,可以用 blob:
fetch('/images/photo.jpg')
.then(response => response.blob())
.then(blob => {
const img = document.getElementById('myPhoto');
img.src = URL.createObjectURL(blob);
});
发送带参数的请求
实际项目中,常需要提交数据,比如用户登录。这时可以配置 fetch 的第二个参数选项:
fetch('/api/login', {
method: 'POST',
headers: {
'Content-Type': 'application/json'
},
body: JSON.stringify({
username: 'john',
password: '123456'
})
})
.then(response => response.json())
.then(result => {
if (result.success) {
window.location.href = '/dashboard';
}
});
这里设置了请求方法为 POST,指定了内容类型,并将用户名密码转成 JSON 字符串发送出去。服务器验证通过后,页面跳转到控制台。
错误处理别忽视
网络请求不一定总成功。fetch 在网络错误时才会 reject Promise,但 HTTP 状态码如 404 或 500 不会触发 catch,需要手动判断:
fetch('/api/user')
.then(response => {
if (!response.ok) {
throw new Error(`HTTP error! status: ${response.status}`);
}
return response.json();
})
.then(data => console.log(data))
.catch(err => console.error('Fetch failed:', err));
加上这层判断,能更早发现问题,避免程序静默失败。
结合 async/await 更清爽
如果你习惯写同步风格的异步代码,配合 async 和 await,fetch 会更易读:
async function loadUserProfile() {
try {
const response = await fetch('/api/profile');
if (!response.ok) throw new Error('加载失败');
const profile = await response.json();
console.log(profile.name);
} catch (error) {
console.error(error.message);
}
}
这种写法像在写普通函数,但内部却是异步执行,适合复杂逻辑场景。
日常做前端配置时,fetch 已成为标准工具之一。无论是加载配置文件、上报埋点数据,还是与后端 API 打交道,掌握它的基本用法都能让开发效率提升一大截。