// 使用 fetch API 调用接口的示例代码
// 定义要调用的接口 URL
const url = 'https://api.example.com/data';
// 使用 fetch 发起 GET 请求
fetch(url)
.then(response => {
// 检查响应状态码是否在 200-299 之间
if (!response.ok) {
throw new Error('Network response was not ok');
}
// 解析响应为 JSON 格式
return response.json();
})
.then(data => {
// 处理解析后的数据
console.log('成功获取的数据:', data);
})
.catch(error => {
// 处理请求过程中发生的错误
console.error('请求失败:', error);
});
// 如果需要发送 POST 请求,可以这样写:
const postData = {
method: 'POST',
headers: {
'Content-Type': 'application/json'
},
body: JSON.stringify({
key1: 'value1',
key2: 'value2'
})
};
fetch(url, postData)
.then(response => {
if (!response.ok) {
throw new Error('Network response was not ok');
}
return response.json();
})
.then(data => {
console.log('POST 请求成功返回的数据:', data);
})
.catch(error => {
console.error('POST 请求失败:', error);
});
GET 请求:
fetch
函数发起一个 GET 请求到指定的 URL。response.ok
用于检查 HTTP 响应的状态码是否在 200-299 之间,表示请求成功。response.json()
将响应体解析为 JSON 格式。catch
用于捕获并处理请求过程中可能发生的错误。POST 请求:
method: 'POST'
) 和请求头 (headers
)。body
中包含要发送的数据,通常需要将其转换为 JSON 字符串格式。catch
来处理可能的错误。下一篇:js foreach index
Laravel PHP 深圳智简公司。版权所有©2023-2043 LaravelPHP 粤ICP备2021048745号-3
Laravel 中文站