umi-request中间件机制

#积累/umi

主要功能

  • 中间件机制,让开发者优雅地做请求前后的增强处理
  • 拦截器,请求前后改变url或options

中间件使用

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
// 实例化request对象
const request = extend({
errorHandler,
credentials: 'include',
});

// 使用request.use方法
function noLogin(ctx, next){
return next().then(()=>{
const { res } = ctx;
if(typeof res === 'string'){
window.location.href = `/index.php?g=admin&m=public&a=login&redirect_url=${window.location.href}`
}
});
}
// 或者用async/await语法
async function noLogin(ctx, next){
await next();
const { res } = ctx;
if(typeof res === 'string'){
window.location.href = `/index.php?g=admin&m=public&a=login&redirect_url=${window.location.href}`
}
}

function codeError(ctx, next){
return next().then(()=>{
const { res } = ctx;
const { code, msg } = res;
if(code!==0){
message.error(msg)
}
})
}
function logOptions(ctx, next){
const { req } = ctx;
console.log(`请求参数 ${req.url} :`, req.options.data);
return next().then(()=>{
const { res } = ctx;
console.log(`接口响应 ${req.url} :`, res)
})
}

request.use(noLogin, { global: true })
request.use(codeError, { global: true })
request.use(logOptions, { global: true })

拦截器使用

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
// 请求拦截器
function addParams(url, options){
return {
url: `${url}&interceptors=yes`,
options: { ...options, interceptors: true },
};
}
request.interceptors.request.use(addParams);
request.interceptors.request.use(addfix, { global: false })

// 响应拦截器
const appendParams(response, options){
response.headers.append('interceptors', 'yes yo');
return response;
}
request.interceptors.response.use(appendParams);

原理

umi-request实际的执行链:
请求拦截器处理——>中间件执行——>真正发起fetch请求——>响应拦截器处理——>中间件执行——>响应结果给model

  • obj对象,传递给所有拦截器和中间件,也是拦截器和中间件操作的对象。
    1
    2
    3
    4
    5
    6
    const obj = {
    req: { url, options },
    res: null,
    cache: this.mapCache,
    responseInterceptors,
    };
  • dealRequestInterceptors,构建执行请求拦截器的promise链,得到最终的url和options
  • on.execute,按顺序执行中间件,最后执行fetchMiddleware,发出fetch请求;得到response后,执行响应拦截器,并返回一个由中间件响应部分执行代码,倒序组成的promis链,不断执行下去。