数字政务中后台项目的一些工具包,包括 cookie、request 等。
基于 umi-request 封装的请求库,包含错误处理等功能。umi-request 底层使用了 whatwg-fetch 提供的能力。
import { request } from '@aligov/util';
request('/api/list').then(res => { console.log(res); })
详细配置参数间 umi-request 和 whatwg-fetch,下面列出常见用法。
常见用法:
request.get(url, options),默认是 get 方法,所以直接用 request 即可request.post(url, options)request.put(url, options)request.patch(url, options)request.delete(url, options)options 常用属性
params,会作为查询参数附加到 url 上,如 { params: { status: 0 } } 会变为 status=0 添加到 url 上。data,请求发送的 body,使用于 post,put 和 patch 方法requestType,data 数据的类型,可选值有 json 和 form,默认是 jsoncache,fetch 请求的 cache 参数,库默认设置为 no-store。no-store 和 no-cache 时,对于 GET 请求和 HEAD 请求,接口 url 添加了 __noCache__=${timestamp} 的参数。如果需要缓存,那么可以设置为 default。如果不需要缓存,但 __noCache__ 和请求的参数冲突,那么可以先设为 default,再自行给 url 添加不冲突属性来防止缓存。options.extraOptions umi-request 扩展属性
autoShowError: boolean,如果设置了,那么会自动展示错误信息;设置为 false 则可不自动使用内置的方案来提示,而是自行处理,包括捕捉但不展示。默认为 true。errorTitle: string,如果设置了,那么作为错误提示的标题,默认为空showErrorTitle: boolean,如果没设置 errorTitle,并且选项为 true,那么根据请求状态来获取错误描述信息来作为错误提示标题,默认为 falsewindow.__autoLogin__ === true 时会在要求登录时自动跳转到 /login 页面。
获取 csrf token,目前是从 cookie 中获取 ctoken 的值。
import { getCToken } from '@aligov/util';
getCToken();
import { url } from '@aligov/util';
const urlObj = url.parse(location.search);
const link = url.format(urlObj);
基于 url。
import { cookie } from '@aligov/util';
cookie.get('cookie-name');
基于 js-cookie。
本 Demo 演示一行文字的用法。
import { request } from '@aligov/util';
request('/api/404')
.catch(err => {
console.log(err.message);
});
request.get('/api/h', {params: {a: 1, b: 2}});
request.post('/api/h', {data: {a: 1, b: 2}});
request('/api/404', {
extraOptions: {
autoShowError: false
}
}).catch(err => {
console.log('custom error', err.message);
});