// 使用 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 请求到指定的 URL。.then(response => { ... })
接收响应对象,并检查响应是否成功(response.ok
)。response.json()
将响应体解析为 JSON 格式。POST 请求:
postData
。fetch('https://api.example.com/posts', postData)
发起一个 POST 请求。通过这种方式,你可以轻松地使用 fetch
API 进行网络请求。
上一篇:nodejs fetch
下一篇:js sleep函数
Laravel PHP 深圳智简公司。版权所有©2023-2043 LaravelPHP 粤ICP备2021048745号-3
Laravel 中文站