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;
    });
}

axios(阿克晓奥丝,爱可信)

axios:基于promise封装的ajax库,基于这个类库发送ajax请求,默认就是基于promise管理的
核心还是XMLHttpRequest
官网

axios.get/head/delete/options/post/put/patch 发送对应类别请求的方法

GET系列:axios.get([url],[config]) 请求URL地址、配置项
POST系列:axios.post([url],[data],[config]) 请求URL地址、请求主体信息、配置项
配置项:
[object]都是plain object纯粹对象

  • params:[string/object] 基于问号参数方案,需要传递给服务器的信息,如果传递的是个对象,axios内部会把对象变为 xxx=xxx&xxx=xxx 这样的字符串,然后基于问号参数传递给服务器;如果写的是一个字符串,则变为 0=字符串 的方式传递给服务器;我们一般都使用对象的方式!!

  • headers:[object] 设置请求头信息,例如:headers:{ 'Content-Type': 'application/x-www-form-urlencoded' } 设定客户端传递给服务器的内容格式是urlencoded格式

  • timeout:[number] 设置超时时间 写零是不设置,单位是MS

  • withCredentials:[boolean] 跨域请求中是否允许携带资源凭证 默认是false

  • responseType:[string] 把服务器返回的结果转换为对应的数据格式 默认是json「服务器返回的结果,我们都把其变为JSON格式的对象」、'arraybuffer', 'blob', 'document', 'json', 'text', 'stream'

  • onUploadProgress:[function] 监听文件上传的进度

  • baseURL:[string] 请求地址的公共前缀

  • transformRequest:[function] POST系列请求,对请求主体的数据进行格式化处理

  • validateStatus:[function] 预设服务器返回的HTTP状态码是多少才算请求成功,默认是以2开始的算成功

基于axios发送的请求,返回结果都是promise实例

  • 数据请求成功会让promise状态为成功,promise值就是从服务器获取的结果
  • 数据请求失败会让promise状态为失败
    • 服务器有响应信息,但是状态码不是以2开始的:reason对象中有response属性,存储服务器返回的信息
    • 请求超时或者被中断 code:"ECONNABORTED" response:undefined
    • 断网了 navigator.onLine=false
axios.get('http://127.0.0.1:9999/user/list', {
  timeout: 1,
  params: {
    departmentId: 0,
    search: ''
  }
}).then(response => {
  console.log('请求成功:', response);
  // response对象
  //   + status/statusText HTTP状态码及其描述
  //   + request 原生的XHR对象
  //   + headers 存储响应头信息(对象)
  //   + config 存储发送请求时候的相关配置项
  //   + data 存储响应主体信息
  return response.data;
}).then(value => {
  console.log('响应主体信息:', value);
}).catch(reason => {
  console.log('请求失败:');
  console.dir(reason);
});

AXIOS处理POST系列请求:

@1 我们DATA(请求主体)写的是一个对象,内部默认处理成为JSON格式的字符串,然后传递给服务器「因为:用AJAX基于请求主体传递给服务器的内容格式有限制 字符串{URLENCODED格式、JSON格式、普通...}、ArrayBuffer、Blob、FormData格式对象」

@2 如果服务器要求传递的格式不是JSON字符串,我们可以给DATA设置值是自己想要的字符串格式
如果要求传递的是 urlencoded 格式字符串,我们可以基于 Qs.stringify/parse 进行处理「引入QS库」

有一个配置项专门是用来处理POST请求,请求主体的数据格式的:transformRequest

  • data传递的依然是个对象格式「常用写法」
  • transformRequest:(data,headers)=>{ return xxx; }

AXIOS内部做了一个非常有用的事情:根据我们传递给服务器的内容格式,自动帮我们设置请求头中的 Content-Type ,让其和传递的格式相匹配「MIME类型」
urlencoded格式字符串 Content-Type:'application/x-www-form-urlencoded'
json格式字符串 Content-Type:'application/json'
FormData格式对象 Content-Type:'multipart/form-data'
...

const qs = require('querystring');

// 验证是否为纯粹的对象
const isPlainObject = function isPlainObject(obj) {
  let proto, Ctor;
  if (!obj || Object.prototype.toString.call(obj) !== "[object Object]") return false;
  proto = Object.getPrototypeOf(obj);
  if (!proto) return true;
  Ctor = proto.hasOwnProperty('constructor') && proto.constructor;
  return typeof Ctor === "function" && Ctor === Object;
};

axios.post('http://127.0.0.1:9999/user/login', {
  account: '18310612838',
  password: md5('1234567890')
}, {
  transformRequest: data => {
    // data:我们传递的这个对象
    // return什么值,就是把其基于请求主体专递给服务器
    if (isPlainObject(data)) return qs.stringify(data);
    return data;
  }
}).then(response => {
  return response.data;
}).then(value => {
  console.log('请求成功', value);
}).catch(reason => {
  // 根据不同的情况做不同提示
});

项目中对 axios 的封装使用

Axios的二次配置:把多个请求之间公共的部分进行提取,后期在业务中再次发送数据请求,公共部分无需再次编写

  • axios.defaults.xxx
  • axios.interceptors.request/response 请求/响应拦截器
// 验证是否为纯粹的对象
const isPlainObject = function isPlainObject(obj) {
    let proto, Ctor;
    if (!obj || Object.prototype.toString.call(obj) !== "[object Object]") return false;
    proto = Object.getPrototypeOf(obj);
    if (!proto) return true;
    Ctor = proto.hasOwnProperty('constructor') && proto.constructor;
    return typeof Ctor === "function" && Ctor === Object;
};

// 请求地址的公共前缀:这样后期再发请求的时候,URL地址中公共前缀部分就不需要写了
//   原理:请求URL地址不含“http(s)://”,发送请求的时候会把baseURL拼上去,然后再发请求;如果自己的URL包含了“http(s)://”这个部分,则以自己的为主,就不在去拼接baseURL了;
axios.defaults.baseURL = 'http://127.0.0.1:9999';

// 根据当前服务器的要求,对于POST系列请求,请求主体传递给服务器的格式都是:urlencoded格式字符串
axios.defaults.transformRequest = data => {
    if (isPlainObject(data)) return Qs.stringify(data);
    return data;
};

// 其它可提取的公共配置部分
axios.defaults.timeout = 60000;
axios.defaults.withCredentials = true;
axios.defaults.validateStatus = status => {
    // 校验服务器返回状态码为多少才算请求成功:默认以2开始才算
    return status >= 200 && status < 400;
};

// 基于拦截器进行公共部分提取
//   + 请求拦截器:发生在 “配置项准备完毕” 和 “发送请求” 之间
//   + 响应拦截器:发生在 “服务器返回结果” 和 “业务代码自己处理 .then” 之间
axios.interceptors.request.use(config => {
    // config对象包含的就是准备好的配置项,最后返回啥配置,就按照这些配置发请求
    return config;
});

axios.interceptors.response.use(response => {
    // 请求成功:把响应主体信息返回给业务层去使用
    return response.data;
}, reason => {
    // 请求失败:根据不同的失败原因做不同的提示
    if (reason && reason.response) {
        // @1 有返回结果,只不过状态码不对
        let {
            status
        } = reason.response;
        switch (+status) {
            case 403:
                alert('服务器不爱搭理你~~');
                break;
            case 404:
                alert('你傻啊,地址都错了~~');
                break;
            case 500:
                alert('服务器开小差了~~');
                break;
        }
    } else {
        // @2 请求超时或者中断 
        if (reason && reason.code === "ECONNABORTED") {
            alert('请求超时或者被中断了~~');
        }
        // @3 断网
        if (!navigator.onLine) {
            alert('当前网络出问题了~~');
        }
    }
    // 统一失败提示处理完,到业务代码处,我们还是要失败的状态,这样才能继续做一些自己单独想做的失败处理
    return Promise.reject(reason);
});

相关文章: