axios
步骤一
下载插件
npm install axios -S
步骤二
创建api文件夹下api.ts文件
import axios from "axios";
axios.defaults.timeout = 30000;
axios.defaults.baseURL = process.env.VUE_APP_API_URL;
// if(process.env.VUE_APP_MODE==='development'){
// console.log('开发');
// }else if(process.env.VUE_APP_MODE==='test'){
// console.log('测试');
// }else{
// console.log('正式');
// }
axios.interceptors.response.use(function (response):any{
if (response.status == 200) {
return response;
}
},function (err) {
return Promise.reject(err);
});
export function apiGet(url:any , params:any) {
return new Promise((resolve, reject) => {
axios.get(url,{
params: params,
headers:{"token":sessionStorage.getItem('token')}
}).then((res) => {
resolve(res.data);
}).catch(err => {
reject(err.data)
})
});
}
export function apiPost(url:any, params:any) {
return new Promise((resolve, reject) => {
axios({
method:'post',
url: url,
data:params
}).then((res) => {
resolve(res.data);
}).catch(err => {
reject(err.data)
})
});
}
步骤三
创建api文件夹下http.ts文件
不传参的情况下可以传个{ } (空) ,不然会报错说只传入了一个参
import { apiGet,apiPost } from './api'
export function getvercode(){
return new Promise<any>((resolve , reject) => {
apiGet('http://47.94.4.201/index.php/index/index/getcode', {}).then((res:any) =>{
resolve(res)
}).catch((err:any) =>{
reject(err)
})
})
}
export function getverLogin(data:any){
return new Promise<any>((resolve , reject) => {
apiPost('http://47.94.4.201/index.php/index/index/login', data).then((res:any) =>{
resolve(res)
}).catch((err:any) =>{
reject(err)
})
})
}
步骤四
在main.ts里面引入全局
import { apiGet,apiPost } from './api/api'
import axios from "axios"
const app = createApp(App)
app.provide("$apiGet",apiGet)
app.provide("$apiPost",apiPost)
步骤五
在正文中使用
import { getvercode , getverLogin} from '../api/http'
//登录
getverLogin(obj).then(res => {
console.log(obj);
if (res.code == 0) {
ElMessage({
message: '登录成功!',
type: 'success',
})
sessionStorage.setItem('zcl', '111')
router.push('/')
} else {
ElMessage({
type: 'error',
message: `登陆失败,信息有误 ?`,
})
}
})
//验证码
getvercode().then(res => {
echo.value = res.msg
})