ajaxSetup() 相当于 Fetch API

Mat*_*aly 5 javascript fetch-api

我是第一次使用Fetch API 。它是否有类似于 jQuery 的ajaxSetup()方法的东西,以便为将来的请求设置授权标头?我找不到任何证据表明它确实如此。

Jai*_*dhu 3

您可以使用 Request 创建授权标头,保存到变量使其可重用。请注意,根据 jQuery 文档,不建议使用 jQuery.ajaxSetup() 设置默认值

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'
   })
});
Run Code Online (Sandbox Code Playgroud)

然后照常使用 fetch 请求

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);
});
Run Code Online (Sandbox Code Playgroud)