Headers

Fetch API 引入三个新的对象(也是构造函数):Headers, RequestResponse。其中,Headers对象用来构造/读取 HTTP 数据包的头信息。

  1. var content = 'Hello World';
  2. var headers = new Headers();
  3. headers.append('Accept', 'application/json');
  4. headers.append('Content-Type', 'text/plain');
  5. headers.append('Content-Length', content.length.toString());
  6. headers.append('X-Custom-Header', 'ProcessThisImmediately');

Headers对象的实例,除了使用append方法添加属性,也可以直接通过构造函数一次性生成。

  1. var reqHeaders = new Headers({
  2. 'Content-Type': 'text/plain',
  3. 'Content-Length': content.length.toString(),
  4. 'X-Custom-Header': 'ProcessThisImmediately',
  5. });

Headers 对象实例还提供了一些工具方法。

  1. reqHeaders.has('Content-Type') // true
  2. reqHeaders.has('Set-Cookie') // false
  3. reqHeaders.set('Content-Type', 'text/html')
  4. reqHeaders.append('X-Custom-Header', 'AnotherValue')
  5. reqHeaders.get('Content-Length') // 11
  6. reqHeaders.getAll('X-Custom-Header') // ["ProcessThisImmediately", "AnotherValue"]
  7. reqHeaders.delete('X-Custom-Header')
  8. reqHeaders.getAll('X-Custom-Header') // []

生成 Header 实例以后,可以将它作为第二个参数,传入Request方法。

  1. var headers = new Headers();
  2. headers.append('Accept', 'application/json');
  3. var request = new Request(URL, {headers: headers});
  4. fetch(request).then(function(response) {
  5. console.log(response.headers);
  6. });

同样地,Headers 实例可以用来构造 Response 方法。

  1. var headers = new Headers({
  2. 'Content-Type': 'application/json',
  3. 'Cache-Control': 'max-age=3600'
  4. });
  5. var response = new Response(
  6. JSON.stringify({photos: {photo: []}}),
  7. {'status': 200, headers: headers}
  8. );
  9. response.json().then(function(json) {
  10. insertPhotos(json);
  11. });

上面代码中,构造了一个 HTTP 回应。目前,浏览器构造 HTTP 回应没有太大用处,但是随着 Service Worker 的部署,不久浏览器就可以向 Service Worker 发出 HTTP 回应。