功能点
| 文件名 |
功能点简介 |
| fetch.js |
请求封装 |
| parseResponse.js |
封装响应的返回 |
| simpleGet.js |
对get请求的封装 |
| simplePost.js |
对post请求的封装 |
fetch.js源码
import 'isomorphic-fetch';import { timeout2Throw, cancel2Throw, getEnv } from '../utils';// 是否已经警告过let warnedCoreType = false;// 默认缓存判断,开放缓存判断给非 get 请求使用function __defaultValidateCache(url, options) { const { method = 'get' } = options; return method.toLowerCase() === 'get';}/** * lamia * fetchMiddleware: 请求的中间件 * @param {*} ctx: 请求中间层封装 * req: { * url: 地址 * options: { * method: 请求方式, * params: url请求参数, * data: 提交的数据 * headers: fetch 原有参数, * timeout: 超时时长, 默认毫秒, 写操作慎用, * prefix: 前缀, 一般用于覆盖统一设置的prefix, * suffix: 后缀, 比如某些场景 api 需要统一加 .json, * credentials: fetch 请求包含 cookies 信息, * useCache: 是否使用缓存(仅支持浏览器客户端), * validateCache: 缓存策略函数 * ttl:缓存时长, 0 为不过期 * maxCache: 最大缓存数 * requestType:post请求时数据类型, * parseResponse:是否对 response 做处理简化, * charset:字符集, * responseType: 如何解析返回的数据 * throwErrIfParseFail:当 responseType 为 'json', 对请求结果做 JSON.parse 出错时是否抛出异常, * getResponse: 是否获取源response, 返回结果将包裹一层, * errorHandler: 异常处理, 或者覆盖统一的异常处理, * cancelToken:取消请求的 Token * } * } * cache: 缓存配置 * responseInterceptors 响应拦截器, 处理响应返回值 * * * @param {*} next: 执行下一步 */export default function fetchMiddleware(ctx, next) { // 如果ctx不存在,则执行下一步 if (!ctx) return next(); // 获取对应的ctx const { req: { options = {}, url = '' } = {}, cache, responseInterceptors } = ctx; const { // 超时时长, 默认毫秒, 写操作慎用 timeout = 0, // __umiRequestCoreType__: 内核请求类型 __umiRequestCoreType__ = 'normal', // 是否使用缓存(仅支持浏览器客户端) useCache = false, // 请求方式 method = 'get', // url请求参数 params, // 缓存时长, 0 为不过期 ttl, // 缓存策略函数 validateCache = __defaultValidateCache, } = options; // 核心请求类型如果并非正常类型 if (__umiRequestCoreType__ !== 'normal') { // 如果是开发环境,则给出友好提示 if (process && process.env && process.env.NODE_ENV === 'development' && warnedCoreType === false) { warnedCoreType = true; console.warn( '__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.' ); } // 开启下一步请求 return next(); } // 定义请求适配器 const adapter = fetch; // 如果请求适配器不存在,则直接异常报错 if (!adapter) { throw new Error('Global fetch not exist!'); } // 从缓存池检查是否有缓存数据 // 用于判断是否为浏览器 const isBrowser = getEnv() === 'BROWSER'; // 判断是否需要缓存 const needCache = validateCache(url, options) && useCache && isBrowser; // 如果需要缓存 if (needCache) { let responseCache = cache.get({ url, params, method, }); if (responseCache) { responseCache = responseCache.clone(); responseCache.useCache = true; ctx.res = responseCache; return next(); } } // 定义响应 let response; // 超时处理 if (timeout > 0) { // 同时执行,并返回对应的组合响应 response = Promise.race([cancel2Throw(options, ctx), adapter(url, options), timeout2Throw(timeout, ctx.req)]); } else { // 不需要超时处理,则执行要取消操作及请求操作 response = Promise.race([cancel2Throw(options, ctx), adapter(url, options)]); } // 兼容老版本 response.interceptor // 拦截器的处理 responseInterceptors.forEach(handler => { response = response.then(res => { // Fix multiple clones not working, issue: https://github.com/github/fetch/issues/504 let clonedRes = typeof res.clone === 'function' ? res.clone() : res; return handler(clonedRes, options); }); }); // 返回最终的响应对象,如果需要缓存处理,则将请求设置到对应的缓存中 return response.then(res => { // 是否存入缓存池 if (needCache) { if (res.status === 200) { const copy = res.clone(); copy.useCache = true; cache.set({ url, params, method }, copy, ttl); } } ctx.res = res; return next(); });}
parseResponse.js源码
import 'isomorphic-fetch';import { timeout2Throw, cancel2Throw, getEnv } from '../utils';// 是否已经警告过let warnedCoreType = false;// 默认缓存判断,开放缓存判断给非 get 请求使用function __defaultValidateCache(url, options) { const { method = 'get' } = options; return method.toLowerCase() === 'get';}/** * lamia * fetchMiddleware: 请求的中间件 * @param {*} ctx: 请求中间层封装 * req: { * url: 地址 * options: { * method: 请求方式, * params: url请求参数, * data: 提交的数据 * headers: fetch 原有参数, * timeout: 超时时长, 默认毫秒, 写操作慎用, * prefix: 前缀, 一般用于覆盖统一设置的prefix, * suffix: 后缀, 比如某些场景 api 需要统一加 .json, * credentials: fetch 请求包含 cookies 信息, * useCache: 是否使用缓存(仅支持浏览器客户端), * validateCache: 缓存策略函数 * ttl:缓存时长, 0 为不过期 * maxCache: 最大缓存数 * requestType:post请求时数据类型, * parseResponse:是否对 response 做处理简化, * charset:字符集, * responseType: 如何解析返回的数据 * throwErrIfParseFail:当 responseType 为 'json', 对请求结果做 JSON.parse 出错时是否抛出异常, * getResponse: 是否获取源response, 返回结果将包裹一层, * errorHandler: 异常处理, 或者覆盖统一的异常处理, * cancelToken:取消请求的 Token * } * } * cache: 缓存配置 * responseInterceptors 响应拦截器, 处理响应返回值 * * * @param {*} next: 执行下一步 */export default function fetchMiddleware(ctx, next) { // 如果ctx不存在,则执行下一步 if (!ctx) return next(); // 获取对应的ctx const { req: { options = {}, url = '' } = {}, cache, responseInterceptors } = ctx; const { // 超时时长, 默认毫秒, 写操作慎用 timeout = 0, // __umiRequestCoreType__: 内核请求类型 __umiRequestCoreType__ = 'normal', // 是否使用缓存(仅支持浏览器客户端) useCache = false, // 请求方式 method = 'get', // url请求参数 params, // 缓存时长, 0 为不过期 ttl, // 缓存策略函数 validateCache = __defaultValidateCache, } = options; // 核心请求类型如果并非正常类型 if (__umiRequestCoreType__ !== 'normal') { // 如果是开发环境,则给出友好提示 if (process && process.env && process.env.NODE_ENV === 'development' && warnedCoreType === false) { warnedCoreType = true; console.warn( '__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.' ); } // 开启下一步请求 return next(); } // 定义请求适配器 const adapter = fetch; // 如果请求适配器不存在,则直接异常报错 if (!adapter) { throw new Error('Global fetch not exist!'); } // 从缓存池检查是否有缓存数据 // 用于判断是否为浏览器 const isBrowser = getEnv() === 'BROWSER'; // 判断是否需要缓存 const needCache = validateCache(url, options) && useCache && isBrowser; // 如果需要缓存 if (needCache) { let responseCache = cache.get({ url, params, method, }); if (responseCache) { responseCache = responseCache.clone(); responseCache.useCache = true; ctx.res = responseCache; return next(); } } // 定义响应 let response; // 超时处理 if (timeout > 0) { // 同时执行,并返回对应的组合响应 response = Promise.race([cancel2Throw(options, ctx), adapter(url, options), timeout2Throw(timeout, ctx.req)]); } else { // 不需要超时处理,则执行要取消操作及请求操作 response = Promise.race([cancel2Throw(options, ctx), adapter(url, options)]); } // 兼容老版本 response.interceptor // 拦截器的处理 responseInterceptors.forEach(handler => { response = response.then(res => { // Fix multiple clones not working, issue: https://github.com/github/fetch/issues/504 let clonedRes = typeof res.clone === 'function' ? res.clone() : res; return handler(clonedRes, options); }); }); // 返回最终的响应对象,如果需要缓存处理,则将请求设置到对应的缓存中 return response.then(res => { // 是否存入缓存池 if (needCache) { if (res.status === 200) { const copy = res.clone(); copy.useCache = true; cache.set({ url, params, method }, copy, ttl); } } ctx.res = res; return next(); });}
simpleGet.js源码
import { isArray, isURLSearchParams, forEach2ObjArr, isObject, isDate, reqStringify } from '../utils';export function paramsSerialize(params, paramsSerializer) { let serializedParams; let jsonStringifiedParams; // 支持参数自动拼装,其他 method 也可用,不冲突 if (params) { if (paramsSerializer) { serializedParams = paramsSerializer(params); } else if (isURLSearchParams(params)) { serializedParams = params.toString(); } else { if (isArray(params)) { jsonStringifiedParams = []; forEach2ObjArr(params, function(item) { if (item === null || typeof item === 'undefined') { jsonStringifiedParams.push(item); } else { jsonStringifiedParams.push(isObject(item) ? JSON.stringify(item) : item); } }); // a: [1,2,3] => a=1&a=2&a=3 serializedParams = reqStringify(jsonStringifiedParams, { arrayFormat: 'repeat', strictNullHandling: true }); } else { jsonStringifiedParams = {}; forEach2ObjArr(params, function(value, key) { let jsonStringifiedValue = value; if (value === null || typeof value === 'undefined') { jsonStringifiedParams[key] = value; } else if (isDate(value)) { jsonStringifiedValue = value.toISOString(); } else if (isArray(value)) { jsonStringifiedValue = value; } else if (isObject(value)) { jsonStringifiedValue = JSON.stringify(value); } jsonStringifiedParams[key] = jsonStringifiedValue; }); const tmp = reqStringify(jsonStringifiedParams, { arrayFormat: 'repeat', strictNullHandling: true }); serializedParams = tmp; } } } return serializedParams;}// 对请求参数做处理,实现 query 简化、 post 简化export default function simpleGetMiddleware(ctx, next) { if (!ctx) return next(); const { req: { options = {} } = {} } = ctx; const { paramsSerializer, params } = options; let { req: { url = '' } = {} } = ctx; // 将 method 改为大写 options.method = options.method ? options.method.toUpperCase() : 'GET'; // 设置 credentials 默认值为 same-origin,确保当开发者没有设置时,各浏览器对请求是否发送 cookies 保持一致的行为 // - omit: 从不发送cookies. // - same-origin: 只有当URL与响应脚本同源才发送 cookies、 HTTP Basic authentication 等验证信息.(浏览器默认值,在旧版本浏览器,例如safari 11依旧是omit,safari 12已更改) // - include: 不论是不是跨域的请求,总是发送请求资源域在本地的 cookies、 HTTP Basic authentication 等验证信息. options.credentials = options.credentials || 'same-origin'; // 支持类似axios 参数自动拼装, 其他method也可用, 不冲突. let serializedParams = paramsSerialize(params, paramsSerializer); ctx.req.originUrl = url; if (serializedParams) { const urlSign = url.indexOf('?') !== -1 ? '&' : '?'; ctx.req.url = `${url}${urlSign}${serializedParams}`; } ctx.req.options = options; return next();}
simplePost.js源码
import { reqStringify } from '../utils';// 对请求参数做处理,实现 query 简化、 post 简化export default function simplePostMiddleware(ctx, next) { if (!ctx) return next(); const { req: { options = {} } = {} } = ctx; const { method = 'get' } = options; if (['post', 'put', 'patch', 'delete'].indexOf(method.toLowerCase()) === -1) { return next(); } const { requestType = 'json', data } = options; // 数据使用类axios的新字段data, 避免引用后影响旧代码, 如将body stringify多次 if (data) { const dataType = Object.prototype.toString.call(data); if (dataType === '[object Object]' || dataType === '[object Array]') { if (requestType === 'json') { options.headers = { Accept: 'application/json', 'Content-Type': 'application/json;charset=UTF-8', ...options.headers, }; options.body = JSON.stringify(data); } else if (requestType === 'form') { options.headers = { Accept: 'application/json', 'Content-Type': 'application/x-www-form-urlencoded;charset=UTF-8', ...options.headers, }; options.body = reqStringify(data, { arrayFormat: 'repeat', strictNullHandling: true }); } } else { // 其他 requestType 自定义header options.headers = { Accept: 'application/json', ...options.headers, }; options.body = data; } } ctx.req.options = options; return next();}