ajaxSetup() 等效于 Fetch API

ajaxSetup() equivalent for Fetch API

我正在使用 Fetch API for the first time. Does it have something akin to jQuery's ajaxSetup() 方法,以便为以后的请求设置授权 headers?我找不到任何证据证明它确实如此。

您可以使用 Request 创建授权 headers,将其保存到变量中可以重复使用。请注意,根据 jQuery 文档,使用 jQuery.ajaxSetup() 设置默认值是 not recommended

let href = '/linkToPage';
let request = new Request(href, {
   method: 'GET',
   mode: 'same-origin',
   redirect: 'follow',
   headers: new Headers({
      'Content-Type': 'text/plain',
      'X-Requested-With': 'XMLHttpRequest'
   })
});

然后照常使用获取请求

fetch(request).then((response) => {
   if(response.ok) {
      return response.text();
   }
   throw new Error('Network response was not ok.');
}).then((text) => {
   if(text.trim() != ''){
      console.log(text);
   }
}).catch((error) => {
   console.log(error);
});