1.在request.ts封装
import axios from 'axios'
import config from './config'
import {Dialog, Toast} from 'vant'
import qs from 'qs'
const Axios = axios.create({ timeout: 1000 * 6});
Axios.interceptors.request.use(
config => {
return config;
},
error => {
console.log(error);
return Promise.reject(error);
}
);
Axios.interceptors.response.use(
response => {
const res = response.data;
console.log(res);
if (res.code === 1) {
return res;
} else {
Dialog.alert({
message: res.msg,
theme: 'round-button',
}).then(() => {
});
return Promise.reject(res.msg);
}
},
error => {
console.log('---ERR:' + error);
Dialog.alert({
message: '服务请求失败',
theme: 'round-button',
}).then(() => {
});
return Promise.reject(error);
})
function get(url: string, params: unknown) {
Toast.loading({
message: '加载中...',
forbidClick: true,
duration:0
});
const baseURL = localStorage.getItem('baseURL')
return new Promise((resolve, reject) => {
Axios.get(baseURL + url, {
params: params,
}).then(res => {
resolve(res)
}).catch(err => {
reject(err)
}).finally(()=>{
Toast.clear()
})
})
}
function post(url: string, params: unknown) {
Toast.loading({
message: '加载中...',
forbidClick: true,
duration:0
});
const baseURL = localStorage.getItem('baseURL')
let headers={
dataType:'JSON'
}
return new Promise((resolve, reject) => {
Axios.post(baseURL + url, qs.stringify(params)).then(res => {
resolve(res)
}).catch(err => {
reject(err)
}).finally(()=>{
Toast.clear()
})
})
}
export default {
get,
post
}
2.使用
import http from "../api/request";
http.post('/users/sign_up', {username:"admin"}).then((res: any) => {
console.log('请求成功', res);
}).catch(err => {
console.log(err);
})