fetchAPI是JavaScript原生提供的用于发起网络请求的接口,基于Promise设计,比传统的XMLHttpRequest更加简洁易用,支持多种HTTP请求方式,可直接处理JSON等常见格式的返回数据。

fetchAPI基本语法
fetchAPI的基本调用格式非常简单,第一个参数是请求的URL,第二个可选参数是配置对象,用于设置请求方法、请求头、请求体等内容。基本调用示例如下:
// 发起GET请求获取用户列表
fetch('https://ipipp.com/api/user/list')
.then(response => {
// 先判断响应状态是否成功
if (!response.ok) {
throw new Error('请求失败,状态码:' + response.status);
}
// 将响应转换为JSON格式
return response.json();
})
.then(data => {
console.log('获取到的用户数据:', data);
})
.catch(error => {
console.error('请求出错:', error);
});常用请求方式示例
GET请求传递参数
GET请求的参数可以直接拼接在URL后面,示例代码如下:
// 带查询参数的GET请求
const userId = 123;
fetch(`https://ipipp.com/api/user/detail?id=${userId}`)
.then(response => response.json())
.then(data => {
console.log('用户详情:', data);
});POST请求提交数据
POST请求需要在配置对象中设置method为POST,同时配置请求头和请求体,示例代码如下:
// 提交JSON数据的POST请求
const postData = {
username: 'testUser',
age: 25
};
fetch('https://ipipp.com/api/user/add', {
method: 'POST',
headers: {
'Content-Type': 'application/json'
},
body: JSON.stringify(postData)
})
.then(response => response.json())
.then(data => {
console.log('添加用户结果:', data);
})
.catch(error => {
console.error('提交失败:', error);
});其他请求方式
除了GET和POST,也可以使用PUT、DELETE等请求方式,只需要修改配置对象中的method属性即可,示例:
// DELETE请求删除用户
const deleteUserId = 456;
fetch(`https://ipipp.com/api/user/delete?id=${deleteUserId}`, {
method: 'DELETE'
})
.then(response => response.json())
.then(data => {
console.log('删除结果:', data);
});注意事项
- fetch请求默认不会携带Cookie,如果需要携带,需要在配置对象中设置
credentials属性为include。 - fetch只有在网络故障时才会触发catch回调,HTTP状态码为404、500等错误不会进入catch,需要手动判断response.ok属性。
- 如果需要设置请求超时时间,fetch本身没有内置配置,需要结合Promise.race方法自行实现。
- 跨域请求时需要服务端配置对应的CORS响应头,否则请求会被浏览器拦截。
常见问题处理
如果请求返回的不是JSON格式数据,比如是文本,可以使用response.text()方法处理,示例如下:
// 获取文本类型返回数据
fetch('https://ipipp.com/api/config')
.then(response => response.text())
.then(text => {
console.log('配置文本内容:', text);
});如果需要上传文件,可以将文件对象放在FormData中作为请求体,不需要手动设置Content-Type,浏览器会自动处理边界值:
// 上传文件示例
const fileInput = document.querySelector('input[type="file"]');
const formData = new FormData();
formData.append('file', fileInput.files[0]);
formData.append('type', 'avatar');
fetch('https://ipipp.com/api/upload', {
method: 'POST',
body: formData
})
.then(response => response.json())
.then(data => {
console.log('上传结果:', data);
});
fetchAPIJavaScript异步请求HTTP请求修改时间:2026-06-07 03:21:25