使用fetch调用接口代码公用写法

问:

现在有一个接口, 我希望你使用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));

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值