fetch请求(请求后端数据的一种方法)

时间:2025-04-26 14:29:39

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

一、发起get请求

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

二、发起post请求

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

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

三、处理请求头

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

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

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

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

五、处理跨域

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

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

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

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

// 取消请求
();

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