Response 和 Request 类似,表示的是一次请求返回的响应数据。下面我们先看下规范中定义了哪些接口。
[Constructor(optional BodyInit? body = null, optional ResponseInit init), Exposed=(Window,Worker)]interface Response {[NewObject] static Response error();[NewObject] static Response redirect(USVString url, optional unsigned short status = 302);readonly attribute ResponseType type;readonly attribute USVString url;readonly attribute boolean redirected;readonly attribute unsigned short status;readonly attribute boolean ok;readonly attribute ByteString statusText;[SameObject] readonly attribute Headers headers;readonly attribute Promise<Headers> trailer;[NewObject] Response clone();};Response includes Body;dictionary ResponseInit {unsigned short status = 200;ByteString statusText = "";HeadersInit headers;};enum ResponseType { "basic", "cors", "default", "error", "opaque", "opaqueredirect" };// 来自 https://fetch.spec.whatwg.org/#response-class
规范中定义的接口我们可以对应着 MDN 进行查看,你可以点击这里更直观的看看它有哪些属性和方法供我们使用,这里不做一一解释。
其中 status, headers 属性最为常用。通过 status 状态码我们可以判断出服务端请求处理的结果,像 200, 403 等等常见状态码。这里举个例子,当 status 为 401 时,可以在前端进行拦截跳转到登录页面,这在现如今 SPA(单页面应用程序)中尤为常见。我们也可以利用 headers 来获取一些服务端返回给前端的信息,比如 token。
仔细看上面的接口的同学可以发现 Response includes Body; 这样的标识。在前面我们说过 Body 由 Request 和 Response 实现。所以 Body 具有的方法,在 Response 实例中都可以使用,而这也是非常重要的一部分,我们通过 Body 提供的方法(这里准确来说是由 Response 实现的)对服务端返回的数据进行处理。
下面我们将通过一个示例来了解下简单用法:
示例
示例代码位置:https://github.com/GoDotDotDot/fe9-fetch-demo/blob/master/views/response.html#L36
// 客户端const headers = new Headers({'X-Token': 'fe9-token-from-frontend',});const request = new Request('/api/response', {method: 'GET',headers,});// 这里我们先发起一个请求试一试fetch(request).then(response => {const { status, headers } = response;document.getElementById('status').innerHTML = `${status}`;document.getElementById('headers').innerHTML = headersToString(headers);return response.json();}).then(resData => {const { status, data } = resData;if (!status) {window.alert('发生了一个错误!');return;}document.getElementById('fetch').innerHTML = data;});
这里我们先忽略 fetch 用法,后面的章节中会进行详细介绍。我们先关注第一个 then 方法回调里面的东西。可以看到返回了一个 response 对象,这个对象就是我们的 Response 的实例。示例中拿了 status 和 headers ,为了方便,这里我将其放到 html 中。再看看该回调中最后一行,我们调用了一个 response.json() 方法(这里后端返的数据是一个 JSON 对象,为了方便直接调用 json()),该方法返回一个 Promise,我们将处理结果返给最后一个 then 回调,这样就可以获得最终处理过后的数据。
打开浏览器,输入 http://127.0.0.1:4000/response,如果你的示例代运行正常,你将会看到以下页面:

(查看 Response 返回的数据)
