fetch

fetch和ajax的区别:fetch代码更加简洁,适用于更高版本浏览器。ajax可以监听到请求过程,兼容性好.......

fetch

注意:由于Fetch API是基于Promise设计,旧浏览器不支持Promise,需要使用pollyfill es6-promise

fetch GET 请求

fetch的第二个参数是可选项,默认的请求方式就是GET请求。

let url = "/address/xxx/xxx?key=value&key2=value2"
fetch(url)
  .then(response => response.json())
  .then(data => {
    // console.log(data);
  })
  .catch(error => {
  // console.log(error)
  })

将对象转成key=value&key2=value2格式的字符串,和地址拼接成 GET 请求的 url

使用qs库

  1. 先 npm 安装。
  2. 引用import { stringify, parse } from 'qs';
  • stringify 将 对象 转成 查询字符串
  • parse 将 查询字符串 转成 对象
    使用举例:
import { stringify } from 'qs';
let Url = "/address/xxx/xxx"
const params = {
  key: value,
  key2: value2
};
let url = `${Url}?${stringify(params)}`
console.log(url) // "/address/xxx/xxx?key=value&key2=value2"

fetch POST 请求

需要设置第二个参数,将其中的method改为POST请求,

let option = {
  method: "POST", // "GET" 、"POST", HTTP请求方法,默认为GET
  headers: { // HTTP的请求头,默认为{}
    Accept: 'application/json',
    'Content-Type': 'application/json; charset=utf-8',
    // 'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8'
  },
  body: "{"a":1,"b":2}", // HTTP的请求参数,一定是字符串,如果不是用下面的转一下
  //body: new URLSearchParams({a:1,b:2}).toString()  // 返回值:"a=1&b=2"。
 //body: JSON.stringify({a:1, b:2, ...}) // 返回值:"{"a":1,"b":2}",将对象形式的参数,转成json。

  credentials: "omit", // 默认为 omit:忽略的意思,也就是不带cookie。"same-origin":意思就是同源请求cookie。"include":表示无论跨域还是同源请求都会带cookie。
}

fetch(url, option)
  .then(response => response.json()) // 后端数据若不是标准JSON时,会报错,可先用e.text()得到字符串
  .then(data => { // 再次.hten之后得到可以使用的数据,开始处理。
    // console.log(data);
  });
  .catch(error => {
  // console.log(error)
  })

fetch()配置对象的完整 API

const response = fetch(url, {
  method: "GET",
  headers: {
    "Content-Type": "text/plain;charset=UTF-8"
  },
  body: undefined,
  referrer: "about:client",
  referrerPolicy: "no-referrer-when-downgrade",
  mode: "cors", 
  credentials: "same-origin",
  cache: "default",
  redirect: "follow",
  integrity: "",
  keepalive: false,
  signal: undefined
});

fetch()请求的底层用的是 Request() 对象的接口,参数完全一样,因此上面的 API 也是Request()的 API。

cache

cache属性指定如何处理缓存。可能的取值如下:

  • default:默认值,先在缓存里面寻找匹配的请求。
  • no-store:直接请求远程服务器,并且不更新缓存。
  • reload:直接请求远程服务器,并且更新缓存。
  • no-cache:将服务器资源跟本地缓存进行比较,有新的版本才使用服务器资源,否则使用缓存。
  • force-cache:缓存优先,只有不存在缓存的情况下,才请求远程服务器。
  • only-if-cached:只检查缓存,如果缓存里面不存在,将返回504错误。

mode

mode属性指定请求的模式。可能的取值如下:

  • cors:默认值,允许跨域请求。
  • same-origin:只允许同源请求。
  • no-cors:请求方法只限于 GET、POST 和 HEAD,并且只能使用有限的几个简单标头,不能添加跨域的复杂标头,相当于提交表单所能发出的请求。

credentials

credentials属性指定是否发送 Cookie。可能的取值如下:

  • same-origin:默认值,同源请求时发送 Cookie,跨域请求时不发送。
  • include:不管同源请求,还是跨域请求,一律发送 Cookie。
  • omit:一律不发送。
    跨域请求发送 Cookie,需要将credentials属性设为include。
fetch('http://another.com', {
  credentials: "include"
});

signal

signal属性指定一个 AbortSignal 实例,用于取消fetch()请求。

keepalive

keepalive属性用于页面卸载时,告诉浏览器在后台保持连接,继续发送数据。

一个典型的场景就是,用户离开网页时,脚本向服务器提交一些用户行为的统计信息。这时,如果不用keepalive属性,数据可能无法发送,因为浏览器已经把页面卸载了。

window.onunload = function() {
  fetch('/analytics', {
    method: 'POST',
    body: "statistics",
    keepalive: true
  });
};

redirect

redirect属性指定 HTTP 跳转的处理方法。可能的取值如下:

  • follow:默认值,fetch()跟随 HTTP 跳转。
  • error:如果发生跳转,fetch()就报错。
  • manual:fetch()不跟随 HTTP 跳转,但是response.url属性会指向新的 URL,response.redirected属性会变为true,由开发者自己决定后续如何处理跳转。

integrity

integrity属性指定一个哈希值,用于检查 HTTP 回应传回的数据是否等于这个预先设定的哈希值。

比如,下载文件时,检查文件的 SHA-256 哈希值是否相符,确保没有被篡改。

fetch('http://site.com/file', {
  integrity: 'sha256-abcdef'
});

referrer

referrer属性用于设定fetch()请求的referer标头。

这个属性可以为任意字符串,也可以设为空字符串(即不发送referer标头)。

fetch('/page', {
  referrer: ''
});

referrerPolicy

referrerPolicy属性用于设定Referer标头的规则。可能的取值如下:

  • no-referrer-when-downgrade:默认值,总是发送Referer标头,除非从 HTTPS 页面请求 HTTP 资源时不发送。
  • no-referrer:不发送Referer标头。
  • origin:Referer标头只包含域名,不包含完整的路径。
  • origin-when-cross-origin:同源请求Referer标头包含完整的路径,跨域请求只包含域名。
  • same-origin:跨域请求不发送Referer,同源请求发送。
  • strict-origin:Referer标头只包含域名,HTTPS 页面请求 HTTP 资源时不发送Referer标头。
  • strict-origin-when-cross-origin:同源请求时Referer标头包含完整路径,跨域请求时只包含域名,HTTPS 页面请求 HTTP 资源时不发送该标头。
  • unsafe-url:不管什么情况,总是发送Referer标头。

对后端返回的数据进行转换

.then(e => e.json()) 这里根据实际情况除了 JSON 以外,还有其它格式的转换,比如:

  • .text() // 将返回体处理成字符串类型
  • .json() // 返回结果和 JSON.parse(responseText)一样
  • .blob() // 返回一个Blob,Blob对象是一个不可更改的类文件的二进制数据
  • .arrayBuffer()
  • .formData()

实际生产过程中封装使用 fetch 的其中一个例子:

// HTTP状态码过滤
function checkStatus(response) {
  if ((response.status >= 200 && response.status < 300)) {
    return response;
  }
  console.log(`请求错误 ${response.status}: ${response.url}: ${response.statusText}`)
  const error = new Error(response.statusText);
  error.response = response;
  throw error;
};

// 数据过滤
function checkData(response) {
  if (response.code === 20000) { // 当code为两万的时候跳转到其它网页
    window.location.href = response.data;
  };
  return response;
};

export default function request(url, options, proxy) {
  const defaultOptions = {
    // credentials: 'same-origin',
    // mode: 'no-cors',
  };
  const newOptions = { ...defaultOptions, ...options };
  if (newOptions.method === 'POST' || newOptions.method === 'PUT') {
    newOptions.headers = {
      Accept: 'application/json',
      'Content-Type': 'application/json; charset=utf-8',
      ...newOptions.headers,
    };
    if (typeof newOptions.body === 'object') {
      newOptions.body = JSON.stringify(newOptions.body);
    }
    // newOptions.mode = 'cors';
  }

  const httpStart = url.indexOf('http');
  let Url = '';
  if (httpStart === 0 || proxy) {
    Url = url; // 以http开头的不加baseUrl
  } else if (window.location.hostname === "localhost") {
    Url = `https://xxx.com${url}`; // 开发环境地址
  } else {
    Url = url // 测试环境 和 生产环境 地址
  };

  // 代理请求需要带上cookie否则导致后端BUC重定向
  if (proxy) {
    newOptions.credentials = 'include';
  };

  return fetch(Url, newOptions)
    .then(checkStatus)
    .then(response => response.json())
    .then(checkData)
    .catch((error) => {
      if (error.code) {
        console.log(error.name, error.message)
      }
      if ('stack' in error && 'message' in error) {
        console.log(url, error.message)
      }
      // 这边需要再斟酌下怎么返回最合适
      return { content: null };
      // return error;
    });
}
posted @ 2018-12-15 16:37  真的想不出来  阅读(522)  评论(0编辑  收藏  举报