@aligov/util

util

Usage no npm install needed!

<script type="module">
  import aligovUtil from 'https://cdn.skypack.dev/@aligov/util';
</script>

README

@aligov/util

数字政务中后台项目的一些工具包,包括 cookie、request 等。

request

基于 umi-request 封装的请求库,包含错误处理等功能。umi-request 底层使用了 whatwg-fetch 提供的能力。

用法

import { request } from '@aligov/util';

request('/api/list').then(res => { console.log(res); })

详细配置参数间 umi-requestwhatwg-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,使用于 postputpatch 方法
  • requestType,data 数据的类型,可选值有 jsonform,默认是 json
  • cachefetch 请求的 cache 参数,库默认设置为 no-storeno-storeno-cache 时,对于 GET 请求和 HEAD 请求,接口 url 添加了 __noCache__=${timestamp} 的参数。如果需要缓存,那么可以设置为 default。如果不需要缓存,但 __noCache__ 和请求的参数冲突,那么可以先设为 default,再自行给 url 添加不冲突属性来防止缓存。

options.extraOptions umi-request 扩展属性

  • autoShowError: boolean,如果设置了,那么会自动展示错误信息;设置为 false 则可不自动使用内置的方案来提示,而是自行处理,包括捕捉但不展示。默认为 true
  • errorTitle: string,如果设置了,那么作为错误提示的标题,默认为空
  • showErrorTitle: boolean,如果没设置 errorTitle,并且选项为 true,那么根据请求状态来获取错误描述信息来作为错误提示标题,默认为 false

window.__autoLogin__ === true 时会在要求登录时自动跳转到 /login 页面。

csrf token

获取 csrf token,目前是从 cookie 中获取 ctoken 的值。

import { getCToken } from '@aligov/util';

getCToken();

url

import { url } from '@aligov/util';

const urlObj = url.parse(location.search);

const link = url.format(urlObj);

基于 url

cookie

import { cookie } from '@aligov/util';

cookie.get('cookie-name');

基于 js-cookie

参考