axios响应数据类型怎么定义?

axios响应数据类型怎么定义?

相关代码

type TResponse = ? // 应该怎么定义
service.interceptors.response.use((response : TResponse) => {
        const res = response.data // 这个结构是固定的 {code:number;msg:string;data:T}
        if (res.code !== 0) {
            return Promise.reject(new Error(res.message || "Error"))
        } else {
            return res
        }
    },
    (error) => {
        return Promise.reject(error)
    }
)


//                         这里code会报错 TS2339: Property  code  does not exist on type  AxiosResponse<any, any> 
 getTableData(fileData).then(({ code, data }) => {
                if (code !== 0) return
  })
阅读 1.1k
3 个回答

举个例子吧:

interface Respones{
    code : number;
    data : any
}
function getTableData(fileData : any){
  return axios.get<void,Respones>('/get')
}

getTableData(fileData)
 .then(({ code, data }) => {}
interface Response extends AxiosResponse {
    "字段": 类型
}


async (...) => {
    const response: Response = await axios.post(...);
}
type ResponseData<T> = {code:number;msg:string;data:T}
import { AxiosResponse } from 'axios';
service.interceptors.response.use(<T>(response:AxiosResponse<ResponseData<T>>) => {
        const res = response.data // 这个结构是固定的 {code:number;msg:string;data:T}
        if (res.code !== 0) {
            return Promise.reject(new Error(res.message || "Error"))
        } else {
            return res
        }
    },
    (error) => {
        return Promise.reject(error)
    }
)

 getTableData(fileData).then(({ code, data }) => {
                if (code !== 0) return
  })

以下是我自己毛遂自荐个人封装的axios的一个写法,可以提供给你参考一下:

api.ts:

export const HOST = process.env.NODE_ENV;
export let BASE_URL = '';
switch (HOST) {
    case 'development':
//开发环境地址
        BASE_URL = '';
        break;
    default:
//生产环境接口地址
        BASE_URL = '';
}

axios.ts:

import axios, { AxiosResponse, InternalAxiosRequestConfig } from 'axios';
// 此处message也可以换成element ui或者element plus等其它组件库的message
// 或者也可以使用我写的轻量消息提示插件ewMessage:https://eveningwater.github.io/ew-message/
import { message as $message } from 'antd';
import { BASE_URL } from './api';

const instance = axios.create({
    baseURL: BASE_URL,
    timeout: 6000
});
instance.interceptors.request.use(
    <T>(
        config:
            | InternalAxiosRequestConfig<T>
            | Promise<InternalAxiosRequestConfig<T>>
    ) => {
        // let token=localStorage.getItem('token');
        // token && (config.headers.Authorization=token);//请求携带token
        // config.headers = {
        //     'Content-Type': 'application/x-www-form-urlencoded'  //转换数据格式
        // }
        return config;
    },
    <T>(error: T) => Promise.reject(error)
);
instance.interceptors.response.use(
    <T>(response: AxiosResponse<T>) => {
        return response;
    },
    (error: { response: { status: number } }) => {
        const { response } = error;
        if (response) {
            //服务器有返回内容
            let errorMsg = '';
            switch (response.status) {
                case 400:
                    errorMsg = '错误请求';
                    break;
                case 401:
                    errorMsg = '未登录,请重新登录';
                    break;
                case 403:
                    errorMsg = '决绝访问';
                    break;
                case 404:
                    errorMsg = '请求错误,未找到该资源';
                    break;
                case 405:
                    errorMsg = '请求方法未允许';
                    break;
                case 408:
                    errorMsg = '请求超时';
                    break;
                case 500:
                    errorMsg = '服务器出错';
                    break;
                case 501:
                    errorMsg = '网络未实现';
                    break;
                case 502:
                    errorMsg = '网络错误';
                    break;
                case 503:
                    errorMsg = '服务不可用';
                    break;
                case 504:
                    errorMsg = '网络超时';
                    break;
                case 505:
                    errorMsg = 'http版本不支持该请求';
                    break;
                default:
                    errorMsg = '连接错误';
            }
            $message.open({ type: 'warning', content: errorMsg });
            return false;
        } else {
            //服务器连结果都没有返回  有可能是断网或者服务器奔溃
            if (!window.navigator.onLine) {
                //断网处理
                $message.open({ content: '网络中断' });
                return;
            } else {
                //服务器奔了
                $message.open({ content: '服务器崩溃了' });
                return Promise.reject(error);
            }
        }
    }
);
export function get<T>(url: string, params?: Record<string, unknown>): Promise<T> {
    return new Promise((resolve, reject) => {
        instance
            .get(url, { params: params })
            .then(res => resolve(res.data))
            .catch(err => reject(err.data));
    });
}
export function post<T>(url: string, params?: Record<string, unknown>): Promise<T> {
    return new Promise((resolve, reject) => {
        instance
            .post(url, params)
            .then(res => resolve(res.data))
            .catch(err => reject(err.data));
    });
}
export function patch<T>(url: string, params?: Record<string, unknown>):Promise<T> {
    return new Promise((resolve, reject) => {
        instance.patch(url, params).then(
            res => resolve(res.data),
            err => reject(err)
        );
    });
}
export function put<T>(url: string, params?: Record<string, unknown>):Promise<T> {
    return new Promise((resolve, reject) => {
        instance.put(url, params).then(
            res => resolve(res.data),
            err => reject(err)
        );
    });
}
export default {
    get,
    post,
    patch,
    put
};

比如有一个接口为addResource.ts:

import { post } from './axios'
// 这里的CommonRes则是你那边定义的 {code:number;msg:string;data:T}
// 参数类型T具体自己定义
export const addResource = <T>(params: T): Promise<CommonRes> => post('xxxx.xxx', { ...params });
推荐问题
logo
Microsoft
子站问答
访问
宣传栏