fetch和ajax的区别

2,235 阅读2分钟

主要有四点区别:

1.fetch默认不带cookie

解决方案:发送带凭据的请求

fetch('https://example.com', {
  credentials: 'same-origin'
})

来源:fetch 不会发送 cookies。除非你使用了credentials 的初始化选项。(自 2017 年 8 月 25 日以后,默认的 credentials 政策变更为 same-origin。Firefox 也在 61.0b13 版本中进行了修改)

它有三种情况:

  1. 为了让浏览器发送包含凭据的请求(即使是跨域源),要将credentials: 'include'添加到传递给 fetch()方法的init对象。

  2. 如果你只想在请求URL与调用脚本位于同一起源处时发送凭据,请添加 credentials: 'same-origin'。

  3. 要改为确保浏览器不在请求中包含凭据,请使用 credentials: 'omit'。

一个基本的 fetch 请求设置起来很简单。看看下面的代码:

fetch

fetch('http://example.com/movies.json')
  .then(function(response) {
    return response.json();
  })
  .then(function(myJson) {
    console.log(myJson);
  });

这里我们通过网络获取一个 JSON 文件并将其打印到控制台。最简单的用法是只提供一个参数用来指明想 fetch() 到的资源路径,然后返回一个包含响应结果的promise(一个 Response 对象)。

当然它只是一个 HTTP 响应,而不是真的JSON。为了获取JSON的内容,我们需要使用 json() 方法(在 Body mixin 中定义,被 Request 和 Response 对象实现)。

2.fetch返回错误的http状态码时不会reject

解决方案:我们可以在第一层.then里面去手动抛出异常

fetch(
        'http://domain/service', {
            method: 'GET'
        }
    )
    .then(response => {
        if (response.ok) {
            return response.json();
        }
        throw new Error('Network response was not ok.');
    })
    .then(json => console.log(json))
    .catch(error => console.error('error:', error));

在手动抛出异常之后我们就可以使用.then .catch了。

3.fetch没有设置超时时间

解决方案:我们可以使用一个promise来封装,通过setTimeout()来设置一个时间,如果超过该时间,就返回reject

    return new Promise((resolve, reject) => {
        fetch(url, init)
            .then(resolve)
            .catch(reject);
        setTimeout(reject, timeout);
    })
}

在这里,fetch会和setTimeout同时执行,因为fetch是异步的,不会堵塞后面setTimeout的执行,这种方式是不是很巧妙。

4.fetch可以中止请求(相当于撤销)

如果我们发送了一个请求,如果又不想发送了,该怎么中止呢? 解决方案:我们可以通过给fetch传递一个参数signal: controller.signal,它是中止控制器AbortController的一个实例

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

var downloadBtn = document.querySelector('.download');
var abortBtn = document.querySelector('.abort');

downloadBtn.addEventListener('click', fetchVideo);

abortBtn.addEventListener('click', function() {
  controller.abort();
  console.log('Download aborted');
});

function fetchVideo() {
  ...
  fetch(url, {signal}).then(function(response) {
    ...
  }).catch(function(e) {
    reports.textContent = 'Download error: ' + e.message;
  })
}

更多可以参考MDN 如果对你有用,记得点点关注哟~