网络请求之Fetch API

637 阅读3分钟

微信公众号:  [大前端驿站]
关注大前端驿站。问题或建议,欢迎公众号留言。 这是我参与8月更文挑战的第17天,活动详情查看:8月更文挑战

Fetch API 能够执行 XMLHttpRequest 对象的所有任务,但更容易使用,接口也更现代化,能够在Web 工作线程等现代 Web 工具中使用。

XMLHttpRequest 可以选择异步,而 Fetch API 则必须是异步。

Fetch API 本身是使用 JavaScript 请求资源的优秀工具,同时这个 API 也能够应用在服务线程(service worker)中,提供拦截、重定向和修改通过 fetch()生成的请求接口。

基本用法

fetch()方法是暴露在全局作用域中的,包括主页面执行线程、模块和工作线程。

发送请求

fetch()只有一个必需的参数 input。多数情况下,这个参数是要获取资源的 URL。这个方法返回一个Promise:

let r = fetch('/bar'); 
console.log(r); // Promise <pending>

请求完成、资源可用时,期约会解决为一个 Response 对象。这个对象是 API 的封装,可以通过它取得相应资源。获取资源要使用这个对象的属性和方法,掌握响应的情况并将负载转换为有用的形式:

fetch('bar.txt') 
 .then((response) => { 
 console.log(response); 
 }); 
// Response { type: "basic", url: ... }
读取响应

读取响应内容的最简单方式是取得纯文本格式的内容,这要用到 text()方法:

fetch('bar.txt') 
 .then((response) => response.text()) 
 .then((data) => console.log(data))
处理状态码和请求失败

Fetch API 支持通过 Response 的 status(状态码)和 statusText(状态文本)属性检查响应状态。成功获取响应的请求通常会产生值为 200 的状态码:

fetch('/bar') 
  .then((response) => { 
    console.log(response.status) // 200 
    console.log(response.statusText) // OK 
  });

请求不存在的资源通常会产生值为 404 的状态码:

fetch('/does-not-exist') 
  .then((response) => { 
    console.log(response.status); // 404 
    console.log(response.statusText); // Not Found 
  });

请求的 URL 如果抛出服务器错误会产生值为 500 的状态码:

fetch('/throw-server-error') 
  .then((response) => { 
    console.log(response.status); // 500 
    console.log(response.statusText); // Internal Server Error 
  });

fetch() 在遇到重定向行为是默认是跟随重定向,跟随重定向时,响应对象的 redirected 属性会被设置为 true,而状态码仍然是 200:

fetch('/permanent-redirect') 
  .then((response) => { 
    // 默认行为是跟随重定向直到最终 URL 
    // 这个例子会出现至少两轮网络请求
    // <origin url>/permanent-redirect -> <redirect url> 
    console.log(response.status); // 200 
    console.log(response.statusText); // OK 
    console.log(response.redirected); // true 
  });

在前面这几个例子中,虽然请求可能失败(如状态码为 500),但都只执行了Promise的解决处理函数。事实上,只要服务器返回了响应,fetch() Promise都会解决。这个行为是合理的:系统级网络协议已经成功完成消息的一次往返传输。至于真正的“成功”请求,则需要在处理响应时再定义。

通常状态码为 200 时就会被认为成功了,其他情况可以被认为未成功。为区分这两种情况,可以在状态码非 200~299 时检查 Response 对象的 ok 属性:

fetch('/bar') 
  .then((response) => { 
    console.log(response.status); // 200 
    console.log(response.ok); // true 
  }); 
fetch('/does-not-exist') 
  .then((response) => { 
    console.log(response.status); // 404 
    console.log(response.ok); // false 
  });

可以通过 url 属性检查通过 fetch()发送请求时使用的完整 URL

fetch('qux').then((response) => console.log(response.url)); 
// https://foo.com/bar/qux



~~ 感谢观看

关注下方【大前端驿站】
让我们一起学,一起进步

【分享、点赞、在看】三连吧,让更多的人加入我们