123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200 |
- import axios from "axios";
- import React from "react";
- import { message } from "antd";
- import { getToken, setToken } from "./token";
-
- const instance = axios.create({
- baseURL: import.meta.env.VITE_SERVER_BASE,
- timeout: 10000,
- // withCredentials: true, // 跨域
- });
-
- // 添加请求拦截器
- instance.interceptors.request.use(
- function (config) {
- const {
- headers = {},
- method = "get",
- responseType = "json",
- download = false,
- silent,
- params = {},
- } = config;
- const token = getToken();
-
- let noTip = silent;
- if (noTip === undefined) {
- noTip = method.toLocaleLowerCase() === "get" ? true : false;
- }
-
- // 在发送请求之前做些什么
- return {
- ...config,
- params,
- silent: noTip,
- headers: {
- "Content-Type": "application/json;charset=utf-8",
- ...headers,
- Authorization: token,
- "x-client-type": "pc.admin",
- },
- responseType: download ? "blob" : responseType,
- };
- },
- function (error) {
- // 对请求错误做些什么
- return Promise.reject(error);
- }
- );
-
- // 添加响应拦截器
- instance.interceptors.response.use(
- function (response) {
- // 1000 范围内的状态码都会触发该函数。
- // 对响应数据做点什么
- const { data, config } = response;
- console.log(response)
- if (config.download && !data.code) {
- return downloadBlob(response, "下载文件");
- }
-
- if (data.code === 200) {
- if (data.data?.token) {
- setToken(data.data.token);
- }
-
- if (!config.silent) {
- message.success("操作成功");
- }
-
- return data.data;
- } else if (data.code === 401) {
- if (!config.silent) {
- message.error("未登录或者超时, 请重新登录");
- }
- } else {
- console.log(config);
- if (!config.silent) {
- const errMsg = data.msg || "系统错误";
- message.error(errMsg.indexOf("exception") > -1 ? "服务异常" : errMsg);
- }
- }
-
- return Promise.reject(response);
- },
- function (error) {
- // 超出 1000 范围的状态码都会触发该函数。
- // 对响应错误做点什么
-
- console.error(error);
-
- return Promise.reject("网络异常, 请重试...");
- }
- );
-
- export default instance;
-
- export function queryTable(apiRequest) {
- return function (params) {
- const { pageSize } = params;
- return apiRequest({
- ...params,
- pageSize,
- pageNum: params.current,
- })
- .then((res) => {
- return {
- data: res.records,
- success: true,
- total: res.total,
- };
- })
- .catch((err) => {
- return {
- success: false,
- };
- });
- };
- }
-
- function getValueOfType(value, type) {
- if (type == "string") return `${value}`;
- if (type == "int" || type == "integer") return value - 0;
- return value;
- }
-
- export function queryDict(
- apiRequest,
- { labelKey = "name", valueKey = "id", valueType }
- ) {
- return function (params) {
- const { current, pageSize, ...leftParams } = params || {};
- return apiRequest({
- pageSize: 9999,
- pageNum: 1,
- ...(leftParams || {}),
- })
- .then((res) => {
- return res?.records?.map((x) => ({
- label: x[labelKey],
- value: getValueOfType(x[valueKey], valueType),
- ...x,
- }));
- })
- .catch((err) => {
- return {
- success: false,
- };
- });
- };
- }
- export function restful(url) {
- const list = (params) => instance.get(url, { params });
- const get = (id) => instance.get(`${url}/${id}`);
- const add = (data) => instance.post(url, data);
- const update = (id, data) => instance.put(`${url}/${id}`, data);
- const del = (id) => instance.delete(`${url}/${id}`);
-
- return [list, get, add, update, del];
- }
-
- export function useRequest(fn) {
- const [loading, setLoading] = React.useState(false);
-
- const p = (...args) =>
- new Promise((resolve, reject) => {
- setLoading(true);
- fn(...args)
- .then((res) => {
- setLoading(false);
- resolve(res);
- })
- .catch((e) => {
- setLoading(false);
- reject(e);
- });
- });
-
- return [loading, p];
- }
-
- function downloadBlob(response) {
- let fileName = "未知文件";
- const contentType = response.headers["content-type"];
- const contentDisposition = response.headers["content-disposition"];
- if (contentDisposition) {
- const parts = contentDisposition.split(";filename=");
- if (parts[1]) {
- fileName = decodeURIComponent(parts[1]);
- }
- }
-
- const url = window.URL.createObjectURL(
- new Blob([response.data], { type: contentType })
- );
- const link = document.createElement("a");
- link.href = url;
- link.setAttribute("download", fileName);
- link.click();
- window.URL.revokeObjectURL(url);
- }
|