//使用 "axios"封装一下请求的接口 vue项目为例
第一部分:request.js内容:
//引入axios
import axios from "axios";
import Cookies from "js-cookie";
const service = axios.create({
baseURL: process.env.MY_PROJECT_URL, // api 的 base_url 也就是代表各个环境 比如dev test 等
timeout: 10000 //默认全部接口的请求的时间
});
// 请求时的拦截器
service.interceptors.request.use(
config => {
//请求的处理 比如处理请求头和TOKEN等等
config.headers.Authorization = Cookies.get("access_token") || "";
config.headers.APP_TOKEN = localStorage.appToken || "";
//处理完允许往下执行请求
return config;
},
error => {
//报错请求抛异常信息
Promise.reject(error);
}
);
// 响应时的拦截器
service.interceptors.response.use(
response => {
// 后端报错处理
if (response.data.code !== "0") {
//一般这里处理的是接口请求报错的各种情况 -- 根据情况自己处理
} else {
// 请求正常
return response;
}
},
error => {
// 系统错误处理 自己根据情况处理
return Promise.reject(error);
}
);
export default service;
第二部分:
以下是使用request.js的处理接口的请求,也就是在api.js中的内容如下:
import request from "@/request";
//这块是后端给的接口url:/apis/demo/app/homePage 只是例子 根据自己项目url不同修改
export const homePage= (obj)=> {
return request({
url: "/apis/demo/app/homePage",
method: "post",
data: obj,
// 单个接口设置请求时间
timeout: 1000
});
}
第三部分:项目页面可以直接的测试封装接口的使用 demo.vue页面为例
<template>
<div></div>
</template>
<script>
import { homePage } from "@/apis/api.js";
export default {
name: "demo",
data() {
return {
data: [],
};
},
created() {
this.demoData();
},
methods: {
//获取getUserList 接口数据
demoData() {
homePage(obj)
.then((res) => {
//接口请求成功逻辑处理
this.data = res.data.data;
console.log(res);
})
.catch((e) => {
//接口异常信息
console.log(e);
});
},
},
};
</script>
第四部分 axios ts源码
index.d.ts文件代码如下:
export interface AxiosTransformer {
(data: any, headers?: any): any;
}
export interface AxiosAdapter {
(config: AxiosRequestConfig): AxiosPromise<any>;
}
export interface AxiosBasicCredentials {
username: string;
password: string;
}
export interface AxiosProxyConfig {
host: string;
port: number;
auth?: {
username: string;
password:string;
};
protocol?: string;
}
export type Method =
| 'get' | 'GET'
| 'delete' | 'DELETE'
| 'head' | 'HEAD'
| 'options' | 'OPTIONS'
| 'post' | 'POST'
| 'put' | 'PUT'
| 'patch' | 'PATCH'
| 'link' | 'LINK'
| 'unlink' | 'UNLINK'
export type ResponseType =
| 'arraybuffer'
| 'blob'
| 'document'
| 'json'
| 'text'
| 'stream'
export interface AxiosRequestConfig {
url?: string;
method?: Method;
baseURL?: string;
transformRequest?: AxiosTransformer | AxiosTransformer[];
transformResponse?: AxiosTransformer | AxiosTransformer[];
headers?: any;
params?: any;
paramsSerializer?: (params: any) => string;
data?: any;
timeout?: number;
timeoutErrorMessage?: string;
withCredentials?: boolean;
adapter?: AxiosAdapter;
auth?: AxiosBasicCredentials;
responseType?: ResponseType;
xsrfCookieName?: string;
xsrfHeaderName?: string;
onUploadProgress?: (progressEvent: any) => void;
onDownloadProgress?: (progressEvent: any) => void;
maxContentLength?: number;
validateStatus?: (status: number) => boolean;
maxRedirects?: number;
socketPath?: string | null;
httpAgent?: any;
httpsAgent?: any;
proxy?: AxiosProxyConfig | false;
cancelToken?: CancelToken;
}
export interface AxiosResponse<T = any> {
data: T;
status: number;
statusText: string;
headers: any;
config: AxiosRequestConfig;
request?: any;
}
export interface AxiosError<T = any> extends Error {
config: AxiosRequestConfig;
code?: string;
request?: any;
response?: AxiosResponse<T>;
isAxiosError: boolean;
toJSON: () => object;
}
export interface AxiosPromise<T = any> extends Promise<AxiosResponse<T>> {
}
export interface CancelStatic {
new (message?: string): Cancel;
}
export interface Cancel {
message: string;
}
export interface Canceler {
(message?: string): void;
}
export interface CancelTokenStatic {
new (executor: (cancel: Canceler) => void): CancelToken;
source(): CancelTokenSource;
}
export interface CancelToken {
promise: Promise<Cancel>;
reason?: Cancel;
throwIfRequested(): void;
}
export interface CancelTokenSource {
token: CancelToken;
cancel: Canceler;
}
export interface AxiosInterceptorManager<V> {
use(onFulfilled?: (value: V) => V | Promise<V>, onRejected?: (error: any) => any): number;
eject(id: number): void;
}
export interface AxiosInstance {
(config: AxiosRequestConfig): AxiosPromise;
(url: string, config?: AxiosRequestConfig): AxiosPromise;
defaults: AxiosRequestConfig;
interceptors: {
request: AxiosInterceptorManager<AxiosRequestConfig>;
response: AxiosInterceptorManager<AxiosResponse>;
};
getUri(config?: AxiosRequestConfig): string;
request<T = any, R = AxiosResponse<T>> (config: AxiosRequestConfig): Promise<R>;
get<T = any, R = AxiosResponse<T>>(url: string, config?: AxiosRequestConfig): Promise<R>;
delete<T = any, R = AxiosResponse<T>>(url: string, config?: AxiosRequestConfig): Promise<R>;
head<T = any, R = AxiosResponse<T>>(url: string, config?: AxiosRequestConfig): Promise<R>;
options<T = any, R = AxiosResponse<T>>(url: string, config?: AxiosRequestConfig): Promise<R>;
post<T = any, R = AxiosResponse<T>>(url: string, data?: any, config?: AxiosRequestConfig): Promise<R>;
put<T = any, R = AxiosResponse<T>>(url: string, data?: any, config?: AxiosRequestConfig): Promise<R>;
patch<T = any, R = AxiosResponse<T>>(url: string, data?: any, config?: AxiosRequestConfig): Promise<R>;
}
export interface AxiosStatic extends AxiosInstance {
create(config?: AxiosRequestConfig): AxiosInstance;
Cancel: CancelStatic;
CancelToken: CancelTokenStatic;
isCancel(value: any): boolean;
all<T>(values: (T | Promise<T>)[]): Promise<T[]>;
spread<T, R>(callback: (...args: T[]) => R): (array: T[]) => R;
}
declare const Axios: AxiosStatic;
export default Axios;