// 使用 fetch API 发起 GET 请求的示例
fetch('https://api.example.com/data')
.then(response => {
if (!response.ok) {
throw new Error('Network response was not ok');
}
return response.json(); // 将响应体解析为 JSON 格式
})
.then(data => {
console.log(data); // 处理从服务器返回的数据
})
.catch(error => {
console.error('There has been a problem with your fetch operation:', error);
});
// 使用 fetch API 发起 POST 请求的示例
const postData = {
method: 'POST',
headers: {
'Content-Type': 'application/json',
},
body: JSON.stringify({
title: 'foo',
body: 'bar',
userId: 1,
}),
};
fetch('https://jsonplaceholder.typicode.com/posts', postData)
.then(response => response.json()) // 将响应体解析为 JSON 格式
.then(data => {
console.log(data); // 处理从服务器返回的数据
})
.catch(error => {
console.error('There has been a problem with your fetch operation:', error);
});
fetch
是一个用于发起网络请求的现代 JavaScript API。它返回一个 Promise
,该 Promise
会在请求完成时解析为 Response
对象。response.ok
检查 HTTP 状态码是否在 200-299 之间,表示请求成功。response.json()
方法将响应体解析为 JSON 格式。catch
块用于捕获并处理可能发生的错误。上一篇:javascript 数组
Laravel PHP 深圳智简公司。版权所有©2023-2043 LaravelPHP 粤ICP备2021048745号-3
Laravel 中文站