axios.interceptors.request.use 请求拦截器
axios.interceptors.response.use 响应拦截器

use方法接收一个参数,为一个callback函数,callback函数用来作为拦截器的处理函数
request.use方法会把 callback放在interceptors_req中,等待执行
response.use方法会把 callback放在interceptors_res中,等待执行

request拦截器的 callback接收的是请求发起前的config
response拦截器的 callback接收的是网络请求的response结果

fetch添加拦截器

fetch.js

  1. const interceptors_req = []; // 请求拦截处理函数集合
  2. const interceptors_res = []; // 响应拦截方法
  3. const initParams = {
  4. method: 'get',
  5. headers: {
  6. Accept: 'application/json',
  7. 'Content-Type': 'application/x-www-form-urlencoded;charset=UTF-8'
  8. },
  9. // body: {}, // Blob、BufferSource、FormData、URLSearchParams
  10. // mode: '', // cors、 no-cors 或者 same-origin
  11. // credentials: 'include', // 跨域传递cookie,omit、same-origin
  12. // cache: '',
  13. }
  14. /**
  15. * 在原生fetch基础之上增加拦截请求的功能
  16. * 封装后,最终暴露在外面的接口应该于原生fetch的使用方法一致,同时增加拦截器功能
  17. * 拦截器的API设计参考axios的拦截器,简化 axios
  18. * @param options
  19. * @param params
  20. * @returns {Promise<unknown>}
  21. * @constructor
  22. */
  23. function Http(options) {
  24. const { url, ...params } = options
  25. // 请求拦截
  26. interceptors_req.forEach(interceptor => {
  27. options = interceptor(options)
  28. })
  29. return new Promise((resolve, reject) => {
  30. return window.fetch(url, params)
  31. .then(res => {
  32. const { status } = res
  33. interceptors_res.forEach(interceptor => {
  34. res = interceptor(res)
  35. })
  36. // 将拦截器处理后的响应结果 resolve出去
  37. if (status >= 200 && status < 300) {
  38. return resolve(res)
  39. }
  40. // 权限不允许则跳转到登陆页面
  41. if (status === 403 || status === 401) {
  42. window.location = '/login'
  43. }
  44. })
  45. .catch(err => reject(err))
  46. });
  47. }
  48. // 拦截器
  49. Http.interceptors = {
  50. request: {
  51. use(callback) {
  52. interceptors_req.push(callback)
  53. },
  54. eject: data => {
  55. if(interceptors_req.indexOf(data) !== -1) {
  56. interceptors_req.splice(interceptors_req.indexOf(data), 1)
  57. }
  58. }
  59. },
  60. response: {
  61. use(callback) {
  62. interceptors_res.push(callback)
  63. },
  64. eject: data => {
  65. if(interceptors_res.indexOf(data) !== -1) {
  66. interceptors_res.splice(interceptors_res.indexOf(data), 1)
  67. }
  68. }
  69. }
  70. }
  71. export default Http
  72. // 使用,请求拦截器
  73. fetch.interceptors.request.use(config => {
  74. return config;
  75. });
  76. // 响应拦截器
  77. fetch.interceptors.response.use(response => {
  78. return response;
  79. });

组件中使用

  1. // 组件中使用
  2. import fetch from './http.js';
  3. // 请求拦截
  4. // 响应拦截
  5. // 清除拦截器