// 使用 fetch 发起 GET 请求
fetch('https://api.example.com/data')
.then(response => {
// 检查响应是否成功
if (!response.ok) {
throw new Error('Network response was not ok');
}
// 将响应体解析为 JSON 格式
return response.json();
})
.then(data => {
// 处理返回的数据
console.log(data);
})
.catch(error => {
// 处理请求过程中发生的错误
console.error('There was a problem with the fetch operation:', error);
});
// 使用 fetch 发起 POST 请求
const postData = {
method: 'POST',
headers: {
'Content-Type': 'application/json'
},
body: JSON.stringify({
title: 'foo',
body: 'bar',
userId: 1
})
};
fetch('https://api.example.com/posts', postData)
.then(response => {
if (!response.ok) {
throw new Error('Network response was not ok');
}
return response.json();
})
.then(data => {
console.log(data);
})
.catch(error => {
console.error('There was a problem with the fetch operation:', error);
});
GET 请求:
fetch('https://api.example.com/data') 发起一个 GET 请求。.then(response => { ... }) 处理响应,检查响应状态并将其解析为 JSON。.catch(error => { ... }) 捕获并处理请求过程中可能发生的错误。POST 请求:
const postData 定义了 POST 请求的配置,包括方法、头部信息和请求体。fetch('https://api.example.com/posts', postData) 发起一个 POST 请求。.then() 和 .catch() 来处理响应和错误。通过这些示例代码,你可以了解如何使用 fetch API 发起 HTTP 请求,并处理响应和错误。
上一篇:js fetch
下一篇:js sleep函数
Laravel PHP 深圳智简公司。版权所有©2023-2043 LaravelPHP 粤ICP备2021048745号-3
Laravel 中文站