前端fetch方法是用于发送请求的方法。可以很方便的获取到后端数据。

一、发起get请求

fetch(url)
//默认返回response,response下有一个json方法可供使用
  .then(response => response.json())
  .then(data => {
    // 处理返回的数据
  })
  .catch(error => {
    // 处理请求错误
  });

二、发起post请求

const data = { /* 请求体数据 */ };

fetch(url, {
  method: 'POST',
  headers: {
    'Content-Type': 'application/json' // 根据实际情况设置请求头
  },
  body: JSON.stringify(data)
})
  .then(response => response.json())
  .then(data => {
    // 处理返回的数据
  })
  .catch(error => {
    // 处理请求错误
  });

三、处理请求头

const headers = new Headers();
headers.append('Authorization', 'Bearer token');

fetch(url, {
  headers: headers
})
  .then(response => response.json())
  .then(data => {
    // 处理返回的数据
  })
  .catch(error => {
    // 处理请求错误
  });

四、处理响应状态。(可以根据响应的状态码来处理不同的情况)

fetch(url)
  .then(response => {
    if (response.ok) {
      // 请求成功
      return response.json();
    } else {
      // 请求失败
      throw new Error('Request failed with status ' + response.status);
    }
  })
  .then(data => {
    // 处理返回的数据
  })
  .catch(error => {
    // 处理请求错误
  });

五、处理跨域

fetch(url, {
  mode: 'cors',
  credentials: 'include' // 发送和接收包含凭据的请求,比如cookie
})
  .then(response => response.json())
  .then(data => {
    // 处理返回的数据
  })
  .catch(error => {
    // 处理请求错误
  });

六、取消请求:
使用AbortControllerAbortSignal可以取消fetch请求。

const controller = new AbortController();
const signal = controller.signal;

fetch(url, { signal })
  .then(response => response.json())
  .then(data => {
    // 处理返回的数据
  })
  .catch(error => {
    if (error.name === 'AbortError') {
      // 请求被取消
    } else {
      // 处理其他请求错误
    }
  });

// 取消请求
controller.abort();

实际开发过程中,建议使用async/awaitaxios简化请求代码

Logo

技术共进,成长同行——讯飞AI开发者社区

更多推荐