hts/apps/blogai/lib/http/service.ts

91 lines
2.3 KiB
TypeScript

// import axiosConfig from "./axios_config";
// import axios from 'axios';
// const service = axios.create(axiosConfig);
// // 请求拦截
// service.interceptors.request.use(
// config => {
// // (config.headers as any).Authorization = 'Bearer' + ' ' + store.getState().chatgpt.token;
// // if (config.data) {
// // config.data = JSON.stringify(config.data);
// // };
// // if (config.method?.toLocaleLowerCase() === 'get') {
// // config.paramsSerializer = function (params) {
// // return qs.stringify(params, { arrayFormat: 'repeat' })
// // }
// // };
// return config;
// },
// ( error: any) => {
// return Promise.reject(error);
// }
// );
// // 响应拦截
// service.interceptors.response.use(
// (res: any) => {
// // let data = JSON.parse(res.data);
// let data = res.data;
// console.log(data)
// return data;
// },
// ( error: { response: { data: string; }; }) => {
// let data = JSON.parse(error.response.data);
// // if (data.code === 500) {
// // console.log(error)
// // };
// return data
// }
// )
// export default service;
import { getAxiosConfig } from "./axios_config";
import axios from "axios";
// 动态生成 axios 实例,每次都能拿到最新 IP
export async function getService() {
const axiosConfig = await getAxiosConfig();
const service = axios.create(axiosConfig);
// 请求拦截
service.interceptors.request.use(
config => {
// (config.headers as any).Authorization = 'Bearer' + ' ' + store.getState().chatgpt.token;
// if (config.data) {
// config.data = JSON.stringify(config.data);
// };
// if (config.method?.toLocaleLowerCase() === 'get') {
// config.paramsSerializer = function (params) {
// return qs.stringify(params, { arrayFormat: 'repeat' })
// }
// };
return config;
},
(error: any) => Promise.reject(error)
);
// 响应拦截
service.interceptors.response.use(
(res: any) => {
let data = res.data;
console.log(data);
return data;
},
(error: { response: { data: string } }) => {
let data = {};
try {
data = JSON.parse(error.response.data);
} catch (e) {
data = error.response?.data || {};
}
return data;
}
);
return service;
}