| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899 |
- import axios, { AxiosRequestConfig, Method } from 'axios'
- //import qs from 'qs'
- //import cryptojs from 'crypto-js'
- import { addPending, removePending } from './pending'
- import { getLoginInfo } from '@/business/common'
- import { HttpRequest, HttpResponse, ResultCode } from './interface'
- //import service from '@/services'
- const http = axios.create({
- timeout: 30000,
- })
- /**
- * 请求拦截器
- */
- http.interceptors.request.use(
- (config) => {
- removePending(config); //在请求开始前,对之前的请求做检查取消操作
- addPending(config); //将当前请求添加到列表中
- //请求头签名
- const sign = {
- token: getLoginInfo('Token'),
- signsecret: 'qz7qWOMXKTMT5JlDs5w4NTPwWeR3xhF1v6wqbZ9cExmP6cc3spvNAp1wJJ1SqRI5',
- timestamp: new Date().getTime(),
- };
- //设置请求头
- config.headers = {
- Authorization: sign.token,
- //Signid: 'eecd3f37625f4501b88e9f0fa14b4b51',
- //Sign: cryptojs.SHA256(qs.stringify(sign)).toString(),
- //Timestamp: sign.timestamp.toString(),
- };
- return config;
- },
- (error) => {
- //此处异常触发条件不明
- console.error(error);
- return Promise.reject('网络异常,请稍后再试');
- }
- )
- /**
- * 响应拦截器
- */
- http.interceptors.response.use(
- (response) => {
- removePending(response); //在请求结束后,移除本次请求
- return response;
- },
- (error) => {
- if (!axios.isCancel(error)) {
- console.error(error);
- }
- return Promise.reject('服务器异常,请稍后再试');
- }
- )
- /**
- * Http请求
- */
- export async function httpRequest<T extends { req?: unknown, rsp?: unknown }>(url: string, method: Method, params: HttpRequest<T>) {
- const { success, fail, complete } = params;
- //const { goCommonSearchUrl } = service.config;
- const requestConfig: AxiosRequestConfig = {
- url,
- method: method,
- }
- if (['post', 'POST', 'put', 'PUT', 'patch', 'PATCH'].includes(method)) {
- requestConfig.data = params.data ?? {};
- } else {
- requestConfig.params = params.data ?? {};
- }
- await http(requestConfig).then((res) => {
- const data = res.data as HttpResponse<T['rsp']>;
- switch (data.code) {
- case ResultCode.InvalidToken:
- //退出登录
- //store.dispatch("user/logout", () => {
- // window.location.reload();
- //});
- return Promise.reject('令牌无效');
- case ResultCode.Success:
- success && success(data);
- return Promise.resolve();
- default:
- return Promise.reject(data.msg);
- }
- }).catch((err) => {
- fail && fail(err);
- return Promise.reject(err);
- }).finally(() => {
- complete && complete();
- })
- }
|