问:
现在有一个接口, 我希望你使用fetch调用这个接口, 有没有公用写法?
回答:
const apiUrl = 'https://xxxx.xxxx.com/xxxx-xxxx/xxxx/xxxx';
// 发起GET请求
fetch(apiUrl)
.then(response => {
if (!response.ok) {
throw new Error('Network response was not ok');
}
return response.json(); // 解析 JSON 格式的响应数据
})
.then(data => {
// 在这里处理从接口返回的数据
console.log('接口返回的数据:', data);
// 例如,将数据显示在页面上
// 假设有一个 id 为 result 的元素用于显示数据
const resultElement = document.getElementById('result');
if (resultElement) {
resultElement.textContent = JSON.stringify(data);
}
})
.catch(error => {
console.error('发生错误:', error);
// 在这里处理错误情况
});
问:
我的fetch请求中可以携带cookie吗?
回答:
fetch('https://example.com/api/data', {
method: 'GET',
credentials: 'include'
})
.then(response => response.json())
.then(data => console.log(data))
.catch(error => console.error('Error fetching data:', error));