123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102 |
- import { extend } from 'umi-request';
- import { Toast } from 'vant';
- import cleanDeep from 'clean-deep';
- import { browser } from '/src/helpers/utils';
- import ApiRouter from '/src/api-router';
- export interface SearchInitParams {
- rows?: string | number;
- page?: string | number;
- }
- export interface InitSearchRespones {
- data: {
- rows: any[],
- [key: string]: any
- };
- [key: string]: any
- }
- const isOpenLogin = false;
- const request = extend({
- requestType: 'form',
- timeout: 10000
- });
- request.use(async (ctx, next) => {
- const { url, options } = ctx.req
- const prefix = options.prefix || '';
- const baseUrl: string = url.replace(prefix, '') || '';
- const linkUrl: string = (ApiRouter as any)[baseUrl];
- if (linkUrl) {
- ctx.req.url = prefix + linkUrl;
- }
- await next();
- })
- request.interceptors.request.use(
- (url, options: any) => {
- const Authorization = sessionStorage.getItem('Authorization') || '';
- const authHeaders: any = {};
- if (
- Authorization &&
- ![
- '/api-auth/usernameLogin',
- '/api-auth/smsLogin',
- '/api-auth/code/sendSms'
- ].includes(url)
- ) {
- authHeaders.Authorization = Authorization
- }
- return {
- url,
- options: {
- ...options,
- params: cleanDeep(options.params),
- headers: {
- ...options.headers,
- ...authHeaders
- }
- }
- }
- },
- { global: false }
- );
- request.interceptors.response.use(
- async res => {
- if (res.status > 299 || res.status < 200) {
- const msg = '服务器错误,状态码' + res.status;
- Toast(msg)
- throw new Error(msg);
- }
- const data = await res.clone().json();
- if (data.code !== 200 && data.errCode !== 0) {
- const msg = data.msg || '处理失败,请重试';
- // const state: any = store.getState()
- // if (data.code === 401 && state.user.status === 'login' && url.pathname !== '/api-auth/exit') {
- // const { dispatch }: any = store
- // dispatch(setLogout())
- // }
- if (!(data.code === 403 || data.code === 401)) {
- Toast(msg);
- }
- const browserInfo = browser()
- if (data.code === 403 && browserInfo.isApp && !isOpenLogin) {
- if (browserInfo.android) {
- (window as any).DAYA.postMessage(JSON.stringify({ api: 'login' }));
- } else if (browserInfo.iPhone) {
- (window as any).webkit.messageHandlers.DAYA.postMessage(
- JSON.stringify({ api: 'login' })
- );
- }
- }
- throw new Error(msg);
- }
- return res;
- },
- { global: false }
- );
- export default request;
|