封装一个axios+vue+ts的ajax请求
时间: 2023-09-08 08:08:21 浏览: 48
以下是一个基于Axios、Vue和TypeScript的封装的Ajax请求示例:
```typescript
import axios, { AxiosRequestConfig, AxiosResponse } from 'axios';
import { Vue } from 'vue-property-decorator';
// 定义全局配置
axios.defaults.baseURL = 'https://api.example.com';
axios.defaults.timeout = 5000;
// 定义请求拦截器
axios.interceptors.request.use((config: AxiosRequestConfig) => {
// 在请求发送前做一些处理,例如添加token等
const token = localStorage.getItem('token');
if (token) {
config.headers.Authorization = `Bearer ${token}`;
}
return config;
}, (error) => {
return Promise.reject(error);
});
// 定义响应拦截器
axios.interceptors.response.use((response: AxiosResponse) => {
// 在响应返回后做一些处理,例如判断是否登录失效等
const data = response.data;
if (data.code === 401) {
Vue.prototype.$message.error('登录失效,请重新登录!');
localStorage.removeItem('token');
location.href = '/login';
}
return response;
}, (error) => {
return Promise.reject(error);
});
// 定义请求方法
export const ajax = {
get<T>(url: string, params?: any): Promise<T> {
return axios.get(url, { params }).then((res: AxiosResponse) => res.data);
},
post<T>(url: string, data?: any): Promise<T> {
return axios.post(url, data).then((res: AxiosResponse) => res.data);
},
put<T>(url: string, data?: any): Promise<T> {
return axios.put(url, data).then((res: AxiosResponse) => res.data);
},
delete<T>(url: string, params?: any): Promise<T> {
return axios.delete(url, { params }).then((res: AxiosResponse) => res.data);
}
};
```
使用时可以直接引入`ajax`对象调用相应的请求方法:
```typescript
import { ajax } from './ajax';
// 发送GET请求
ajax.get('/users', { page: 1, limit: 10 }).then((data) => {
console.log(data);
}).catch((error) => {
console.error(error);
});
// 发送POST请求
ajax.post('/users', { name: '张三', age: 18 }).then((data) => {
console.log(data);
}).catch((error) => {
console.error(error);
});
```