axios安装:
yarn add axios
npm install axios -S
src 下创建 request/http.js
import axios from 'axios';
import {Toast} from 'vant';
// 创建实例
const instance = axios.create({
baseURL: "http://localhost:8080",
timeout: 10000,
});
// 请求拦截
instance.interceptors.request.use(
config => {
// 发送请求前进行拦截操作
return config;
}, err => {
// 请求错误操作
return err;
}
);
// 响应拦截
instance.interceptors.response.use(
res => {
// 响应数据前进行拦截操作
return res;
}, err => {
// 响应错误操作
return err;
}
);
// get 请求
export const get = (url, params) => {
return new Promise((resolve, reject) => {
instance.get(url, {
params: params
})
.then(res => resolve(res))
.catch(err => reject(err))
})
}
// post 请求
export const post = (url, data) => {
return new Promise((resolve, reject) => {
instance.post(url, data)
.then(res => resolve(res))
.catch(err => reject(err))
})
}
// put 请求
export const put = (url, data) => {
return new Promise((resolve, reject) => {
instance.put(url, data)
.then(res => resolve(res))
.catch(err => reject(err))
})
}
// delete 请求
export const del = (url, params) => {
return new Promise((resolve, reject) => {
instance.delete(url, {
params: params
})
.then(res => resolve(res))
.catch(err => reject(err))
})
}
src 下创建 request/api.js
import {get, post, put, del} from "./http";
// get
export const get= params => get("/api/get", params);
// post
export const post = data => post("/api/post", data);
// put
export const put= data => put("/api/put", data);
// del
export const del= params=> del("/api/del", params);
main.js 引入挂载全局
import *as api from './request/api';
Vue.prototype.$api = api;
index.vue 组件调用
created() {
// get 请求
this.$api.get().then(res => console.log(res))
}
原文链接:https://blog.csdn.net/weixin_43963870/article/details/107334949