功能点

文件名 功能点简介
fetch.js 请求封装
parseResponse.js 封装响应的返回
simpleGet.js 对get请求的封装
simplePost.js 对post请求的封装

fetch.js源码

  1. import 'isomorphic-fetch';
  2. import { timeout2Throw, cancel2Throw, getEnv } from '../utils';
  3. // 是否已经警告过
  4. let warnedCoreType = false;
  5. // 默认缓存判断,开放缓存判断给非 get 请求使用
  6. function __defaultValidateCache(url, options) {
  7. const { method = 'get' } = options;
  8. return method.toLowerCase() === 'get';
  9. }
  10. /**
  11. * lamia
  12. * fetchMiddleware: 请求的中间件
  13. * @param {*} ctx: 请求中间层封装
  14. * req: {
  15. * url: 地址
  16. * options: {
  17. * method: 请求方式,
  18. * params: url请求参数,
  19. * data: 提交的数据
  20. * headers: fetch 原有参数,
  21. * timeout: 超时时长, 默认毫秒, 写操作慎用,
  22. * prefix: 前缀, 一般用于覆盖统一设置的prefix,
  23. * suffix: 后缀, 比如某些场景 api 需要统一加 .json,
  24. * credentials: fetch 请求包含 cookies 信息,
  25. * useCache: 是否使用缓存(仅支持浏览器客户端),
  26. * validateCache: 缓存策略函数
  27. * ttl:缓存时长, 0 为不过期
  28. * maxCache: 最大缓存数
  29. * requestType:post请求时数据类型,
  30. * parseResponse:是否对 response 做处理简化,
  31. * charset:字符集,
  32. * responseType: 如何解析返回的数据
  33. * throwErrIfParseFail:当 responseType 为 'json', 对请求结果做 JSON.parse 出错时是否抛出异常,
  34. * getResponse: 是否获取源response, 返回结果将包裹一层,
  35. * errorHandler: 异常处理, 或者覆盖统一的异常处理,
  36. * cancelToken:取消请求的 Token
  37. * }
  38. * }
  39. * cache: 缓存配置
  40. * responseInterceptors 响应拦截器, 处理响应返回值
  41. *
  42. *
  43. * @param {*} next: 执行下一步
  44. */
  45. export default function fetchMiddleware(ctx, next) {
  46. // 如果ctx不存在,则执行下一步
  47. if (!ctx) return next();
  48. // 获取对应的ctx
  49. const { req: { options = {}, url = '' } = {}, cache, responseInterceptors } = ctx;
  50. const {
  51. // 超时时长, 默认毫秒, 写操作慎用
  52. timeout = 0,
  53. // __umiRequestCoreType__: 内核请求类型
  54. __umiRequestCoreType__ = 'normal',
  55. // 是否使用缓存(仅支持浏览器客户端)
  56. useCache = false,
  57. // 请求方式
  58. method = 'get',
  59. // url请求参数
  60. params,
  61. // 缓存时长, 0 为不过期
  62. ttl,
  63. // 缓存策略函数
  64. validateCache = __defaultValidateCache,
  65. } = options;
  66. // 核心请求类型如果并非正常类型
  67. if (__umiRequestCoreType__ !== 'normal') {
  68. // 如果是开发环境,则给出友好提示
  69. if (process && process.env && process.env.NODE_ENV === 'development' && warnedCoreType === false) {
  70. warnedCoreType = true;
  71. console.warn(
  72. '__umiRequestCoreType__ is a internal property that use in umi-request, change its value would affect the behavior of request! It only use when you want to extend or use request core.'
  73. );
  74. }
  75. // 开启下一步请求
  76. return next();
  77. }
  78. // 定义请求适配器
  79. const adapter = fetch;
  80. // 如果请求适配器不存在,则直接异常报错
  81. if (!adapter) {
  82. throw new Error('Global fetch not exist!');
  83. }
  84. // 从缓存池检查是否有缓存数据
  85. // 用于判断是否为浏览器
  86. const isBrowser = getEnv() === 'BROWSER';
  87. // 判断是否需要缓存
  88. const needCache = validateCache(url, options) && useCache && isBrowser;
  89. // 如果需要缓存
  90. if (needCache) {
  91. let responseCache = cache.get({
  92. url,
  93. params,
  94. method,
  95. });
  96. if (responseCache) {
  97. responseCache = responseCache.clone();
  98. responseCache.useCache = true;
  99. ctx.res = responseCache;
  100. return next();
  101. }
  102. }
  103. // 定义响应
  104. let response;
  105. // 超时处理
  106. if (timeout > 0) {
  107. // 同时执行,并返回对应的组合响应
  108. response = Promise.race([cancel2Throw(options, ctx), adapter(url, options), timeout2Throw(timeout, ctx.req)]);
  109. } else {
  110. // 不需要超时处理,则执行要取消操作及请求操作
  111. response = Promise.race([cancel2Throw(options, ctx), adapter(url, options)]);
  112. }
  113. // 兼容老版本 response.interceptor
  114. // 拦截器的处理
  115. responseInterceptors.forEach(handler => {
  116. response = response.then(res => {
  117. // Fix multiple clones not working, issue: https://github.com/github/fetch/issues/504
  118. let clonedRes = typeof res.clone === 'function' ? res.clone() : res;
  119. return handler(clonedRes, options);
  120. });
  121. });
  122. // 返回最终的响应对象,如果需要缓存处理,则将请求设置到对应的缓存中
  123. return response.then(res => {
  124. // 是否存入缓存池
  125. if (needCache) {
  126. if (res.status === 200) {
  127. const copy = res.clone();
  128. copy.useCache = true;
  129. cache.set({ url, params, method }, copy, ttl);
  130. }
  131. }
  132. ctx.res = res;
  133. return next();
  134. });
  135. }

parseResponse.js源码

  1. import 'isomorphic-fetch';
  2. import { timeout2Throw, cancel2Throw, getEnv } from '../utils';
  3. // 是否已经警告过
  4. let warnedCoreType = false;
  5. // 默认缓存判断,开放缓存判断给非 get 请求使用
  6. function __defaultValidateCache(url, options) {
  7. const { method = 'get' } = options;
  8. return method.toLowerCase() === 'get';
  9. }
  10. /**
  11. * lamia
  12. * fetchMiddleware: 请求的中间件
  13. * @param {*} ctx: 请求中间层封装
  14. * req: {
  15. * url: 地址
  16. * options: {
  17. * method: 请求方式,
  18. * params: url请求参数,
  19. * data: 提交的数据
  20. * headers: fetch 原有参数,
  21. * timeout: 超时时长, 默认毫秒, 写操作慎用,
  22. * prefix: 前缀, 一般用于覆盖统一设置的prefix,
  23. * suffix: 后缀, 比如某些场景 api 需要统一加 .json,
  24. * credentials: fetch 请求包含 cookies 信息,
  25. * useCache: 是否使用缓存(仅支持浏览器客户端),
  26. * validateCache: 缓存策略函数
  27. * ttl:缓存时长, 0 为不过期
  28. * maxCache: 最大缓存数
  29. * requestType:post请求时数据类型,
  30. * parseResponse:是否对 response 做处理简化,
  31. * charset:字符集,
  32. * responseType: 如何解析返回的数据
  33. * throwErrIfParseFail:当 responseType 为 'json', 对请求结果做 JSON.parse 出错时是否抛出异常,
  34. * getResponse: 是否获取源response, 返回结果将包裹一层,
  35. * errorHandler: 异常处理, 或者覆盖统一的异常处理,
  36. * cancelToken:取消请求的 Token
  37. * }
  38. * }
  39. * cache: 缓存配置
  40. * responseInterceptors 响应拦截器, 处理响应返回值
  41. *
  42. *
  43. * @param {*} next: 执行下一步
  44. */
  45. export default function fetchMiddleware(ctx, next) {
  46. // 如果ctx不存在,则执行下一步
  47. if (!ctx) return next();
  48. // 获取对应的ctx
  49. const { req: { options = {}, url = '' } = {}, cache, responseInterceptors } = ctx;
  50. const {
  51. // 超时时长, 默认毫秒, 写操作慎用
  52. timeout = 0,
  53. // __umiRequestCoreType__: 内核请求类型
  54. __umiRequestCoreType__ = 'normal',
  55. // 是否使用缓存(仅支持浏览器客户端)
  56. useCache = false,
  57. // 请求方式
  58. method = 'get',
  59. // url请求参数
  60. params,
  61. // 缓存时长, 0 为不过期
  62. ttl,
  63. // 缓存策略函数
  64. validateCache = __defaultValidateCache,
  65. } = options;
  66. // 核心请求类型如果并非正常类型
  67. if (__umiRequestCoreType__ !== 'normal') {
  68. // 如果是开发环境,则给出友好提示
  69. if (process && process.env && process.env.NODE_ENV === 'development' && warnedCoreType === false) {
  70. warnedCoreType = true;
  71. console.warn(
  72. '__umiRequestCoreType__ is a internal property that use in umi-request, change its value would affect the behavior of request! It only use when you want to extend or use request core.'
  73. );
  74. }
  75. // 开启下一步请求
  76. return next();
  77. }
  78. // 定义请求适配器
  79. const adapter = fetch;
  80. // 如果请求适配器不存在,则直接异常报错
  81. if (!adapter) {
  82. throw new Error('Global fetch not exist!');
  83. }
  84. // 从缓存池检查是否有缓存数据
  85. // 用于判断是否为浏览器
  86. const isBrowser = getEnv() === 'BROWSER';
  87. // 判断是否需要缓存
  88. const needCache = validateCache(url, options) && useCache && isBrowser;
  89. // 如果需要缓存
  90. if (needCache) {
  91. let responseCache = cache.get({
  92. url,
  93. params,
  94. method,
  95. });
  96. if (responseCache) {
  97. responseCache = responseCache.clone();
  98. responseCache.useCache = true;
  99. ctx.res = responseCache;
  100. return next();
  101. }
  102. }
  103. // 定义响应
  104. let response;
  105. // 超时处理
  106. if (timeout > 0) {
  107. // 同时执行,并返回对应的组合响应
  108. response = Promise.race([cancel2Throw(options, ctx), adapter(url, options), timeout2Throw(timeout, ctx.req)]);
  109. } else {
  110. // 不需要超时处理,则执行要取消操作及请求操作
  111. response = Promise.race([cancel2Throw(options, ctx), adapter(url, options)]);
  112. }
  113. // 兼容老版本 response.interceptor
  114. // 拦截器的处理
  115. responseInterceptors.forEach(handler => {
  116. response = response.then(res => {
  117. // Fix multiple clones not working, issue: https://github.com/github/fetch/issues/504
  118. let clonedRes = typeof res.clone === 'function' ? res.clone() : res;
  119. return handler(clonedRes, options);
  120. });
  121. });
  122. // 返回最终的响应对象,如果需要缓存处理,则将请求设置到对应的缓存中
  123. return response.then(res => {
  124. // 是否存入缓存池
  125. if (needCache) {
  126. if (res.status === 200) {
  127. const copy = res.clone();
  128. copy.useCache = true;
  129. cache.set({ url, params, method }, copy, ttl);
  130. }
  131. }
  132. ctx.res = res;
  133. return next();
  134. });
  135. }

simpleGet.js源码

  1. import { isArray, isURLSearchParams, forEach2ObjArr, isObject, isDate, reqStringify } from '../utils';
  2. export function paramsSerialize(params, paramsSerializer) {
  3. let serializedParams;
  4. let jsonStringifiedParams;
  5. // 支持参数自动拼装,其他 method 也可用,不冲突
  6. if (params) {
  7. if (paramsSerializer) {
  8. serializedParams = paramsSerializer(params);
  9. } else if (isURLSearchParams(params)) {
  10. serializedParams = params.toString();
  11. } else {
  12. if (isArray(params)) {
  13. jsonStringifiedParams = [];
  14. forEach2ObjArr(params, function(item) {
  15. if (item === null || typeof item === 'undefined') {
  16. jsonStringifiedParams.push(item);
  17. } else {
  18. jsonStringifiedParams.push(isObject(item) ? JSON.stringify(item) : item);
  19. }
  20. });
  21. // a: [1,2,3] => a=1&a=2&a=3
  22. serializedParams = reqStringify(jsonStringifiedParams, { arrayFormat: 'repeat', strictNullHandling: true });
  23. } else {
  24. jsonStringifiedParams = {};
  25. forEach2ObjArr(params, function(value, key) {
  26. let jsonStringifiedValue = value;
  27. if (value === null || typeof value === 'undefined') {
  28. jsonStringifiedParams[key] = value;
  29. } else if (isDate(value)) {
  30. jsonStringifiedValue = value.toISOString();
  31. } else if (isArray(value)) {
  32. jsonStringifiedValue = value;
  33. } else if (isObject(value)) {
  34. jsonStringifiedValue = JSON.stringify(value);
  35. }
  36. jsonStringifiedParams[key] = jsonStringifiedValue;
  37. });
  38. const tmp = reqStringify(jsonStringifiedParams, { arrayFormat: 'repeat', strictNullHandling: true });
  39. serializedParams = tmp;
  40. }
  41. }
  42. }
  43. return serializedParams;
  44. }
  45. // 对请求参数做处理,实现 query 简化、 post 简化
  46. export default function simpleGetMiddleware(ctx, next) {
  47. if (!ctx) return next();
  48. const { req: { options = {} } = {} } = ctx;
  49. const { paramsSerializer, params } = options;
  50. let { req: { url = '' } = {} } = ctx;
  51. // 将 method 改为大写
  52. options.method = options.method ? options.method.toUpperCase() : 'GET';
  53. // 设置 credentials 默认值为 same-origin,确保当开发者没有设置时,各浏览器对请求是否发送 cookies 保持一致的行为
  54. // - omit: 从不发送cookies.
  55. // - same-origin: 只有当URL与响应脚本同源才发送 cookies、 HTTP Basic authentication 等验证信息.(浏览器默认值,在旧版本浏览器,例如safari 11依旧是omit,safari 12已更改)
  56. // - include: 不论是不是跨域的请求,总是发送请求资源域在本地的 cookies、 HTTP Basic authentication 等验证信息.
  57. options.credentials = options.credentials || 'same-origin';
  58. // 支持类似axios 参数自动拼装, 其他method也可用, 不冲突.
  59. let serializedParams = paramsSerialize(params, paramsSerializer);
  60. ctx.req.originUrl = url;
  61. if (serializedParams) {
  62. const urlSign = url.indexOf('?') !== -1 ? '&' : '?';
  63. ctx.req.url = `${url}${urlSign}${serializedParams}`;
  64. }
  65. ctx.req.options = options;
  66. return next();
  67. }

simplePost.js源码

  1. import { reqStringify } from '../utils';
  2. // 对请求参数做处理,实现 query 简化、 post 简化
  3. export default function simplePostMiddleware(ctx, next) {
  4. if (!ctx) return next();
  5. const { req: { options = {} } = {} } = ctx;
  6. const { method = 'get' } = options;
  7. if (['post', 'put', 'patch', 'delete'].indexOf(method.toLowerCase()) === -1) {
  8. return next();
  9. }
  10. const { requestType = 'json', data } = options;
  11. // 数据使用类axios的新字段data, 避免引用后影响旧代码, 如将body stringify多次
  12. if (data) {
  13. const dataType = Object.prototype.toString.call(data);
  14. if (dataType === '[object Object]' || dataType === '[object Array]') {
  15. if (requestType === 'json') {
  16. options.headers = {
  17. Accept: 'application/json',
  18. 'Content-Type': 'application/json;charset=UTF-8',
  19. ...options.headers,
  20. };
  21. options.body = JSON.stringify(data);
  22. } else if (requestType === 'form') {
  23. options.headers = {
  24. Accept: 'application/json',
  25. 'Content-Type': 'application/x-www-form-urlencoded;charset=UTF-8',
  26. ...options.headers,
  27. };
  28. options.body = reqStringify(data, { arrayFormat: 'repeat', strictNullHandling: true });
  29. }
  30. } else {
  31. // 其他 requestType 自定义header
  32. options.headers = {
  33. Accept: 'application/json',
  34. ...options.headers,
  35. };
  36. options.body = data;
  37. }
  38. }
  39. ctx.req.options = options;
  40. return next();
  41. }