Fetch API 与 Axios 在处理请求和响应时有哪些本质上的不同?请举例说明这些不同在实际应用中的影响。

Fetch API 与 Axios 都是用于发送网络请求的工具,但它们之间存在几个关键性的不同点,这些不同点在实际应用中可能会产生不同的影响。

1. 浏览器兼容性

  • Fetch API: 是一个相对较新的浏览器内置 API,因此它的兼容性不像 Axios 那样广泛。在一些旧版本的浏览器(如 IE11)中,Fetch API 可能不可用,需要引入 polyfill 才能使用。
  • Axios: 是一个基于 promise 的 HTTP 客户端,支持所有现代浏览器,甚至包括 IE8。这意味着在不需要考虑新开标签页等问题的项目中,Axios 的兼容性更好。

2. 易用性

  • Fetch API: 使用时需要显式设置请求配置,例如设置请求方法、请求头等。默认情况下,Fetch 不会发送跨域请求中的凭证(如 cookies),除非显式配置。
    fetch('https://api.example.com/data', {
      method: 'POST',
      headers: {
        'Content-Type': 'application/json'
      },
      body: JSON.stringify({id: 123})
    })
    .then(response => response.json())
    .then(data => console.log(data))
    .catch(error => console.error('Error:', error));
    
  • Axios: 提供了更简洁、更直观的 API。例如,设置请求头和发送数据更加简单,同时 Axios 默认支持发送凭证。
    axios.post('https://api.example.com/data', {id: 123}, {
      headers: {
        'Content-Type': 'application/json'
      },
      withCredentials: true
    })
    .then(response => console.log(response.data))
    .catch(error => console.error('Error:', error));
    

3. 错误处理

  • Fetch API: 在请求失败时,fetch 只会返回一个 rejected promise(如果没有网络连接或服务器返回 404 等错误),而对于普通的 HTTP 错误(如 400, 500),fetch 会返回一个 resolved promise。因此,开发者需要在 response.ok 上做检查以处理错误。
    fetch('https://api.example.com/data')
    .then(response => {
      if (!response.ok) {
        throw new Error('Network response was not ok ' + response.statusText);
      }
      return response.json();
    })
    .then(data => console.log(data))
    .catch(error => console.error('Error:', error));
    
  • Axios: 默认情况下,Axios 会直接抛出错误,这使得错误处理更加直观。
    axios.get('https://api.example.com/data')
    .then(response => console.log(response.data))
    .catch(error => {
      if (error.response) {
        // 请求已发出,但服务器响应的状态码不在 2xx 区间内
        console.error('Error:', error.response.data);
      } else {
        // 发生在设置请求或处理响应时的错误
        console.error('Error:', error.message);
      }
    });
    

4. 请求取消

  • Fetch API: 取消请求需要使用 AbortController,并且必须与 fetch 一起使用。
    const controller = new AbortController();
    const signal = controller.signal;
    
    fetch('https://api.example.com/data', { signal })
    .then(response => response.json())
    .then(data => console.log(data))
    .catch(error => console.error('Error:', error));
    
    // 取消请求
    controller.abort();
    
  • Axios: 支持通过 CancelToken 来取消请求,更加方便。
    let cancel
    const source = axios.CancelToken.source();
    
    axios.get('https://api.example.com/data', {
      cancelToken: source.token
    })
    .then(response => console.log(response.data))
    .catch(thrown => {
      if (axios.isCancel(thrown)) {
        console.log('Request canceled', thrown.message);
      } else {
        // 处理错误
        console.error('Error:', thrown);
      }
    });
    
    // 取消请求
    source.cancel('Operation canceled by the user.');
    

5. 请求拦截器和响应拦截器

  • Fetch API: 不提供内置的请求或响应拦截功能,需要手动实现。
  • Axios: 内置了请求和响应的拦截器,可以方便地对请求或响应进行全局处理,如添加请求头、处理响应数据等。
    axios.interceptors.request.use(config => {
      // 在发送请求之前做些什么
      return config;
    }, error => {
      // 对请求错误做些什么
      return Promise.reject(error);
    });
    
    axios.interceptors.response.use(response => {
      // 对响应数据做点什么
      return response;
    }, error => {
      // 对响应错误做点什么
      return Promise.reject(error);
    });
    

实际应用影响

  • 兼容性: 在需要广泛浏览器支持的项目中,Axios 是更好的选择。
  • 易用性: 无论是初学者还是经验丰富的开发者,Axios 的易用性都更高,减少了出错的机会。
  • 错误处理: Axios 的错误处理方式更加直观,减少了开发者的负担。
  • 请求取消: Axios 的请求取消机制更加简单易用。
  • 拦截器: Axios 的拦截器功能在处理全局请求和响应时非常有用,特别是在需要统一处理认证信息、日志记录等场景下。

在实际项目中,选择哪个工具取决于项目的需求和团队的技术栈。对于大多数现代 Web 应用,Axios 是更常用的选择,但在某些特定场景或对性能有极高要求的应用中,Fetch API 也有其用武之地。希望这些信息对您有所帮助!