1.创建utils文件夹并新建request文件(js)
//封装axios
//引入axios和querystring以及route
import axios from "axios";
import qs from "querystring";
import router from "../router/index";
//创建axios实例对象instance
var instance = axios.create({ timeout: 5000 });
// instance.defaults.headers.common["Authorization"] = AUTH_TOKEN;
//因为现在没有token,带上这个会报错,所有先注释
instance.defaults.headers.post["Content-Type"] =
"application/x-www-form-urlencoded";
//跳转登录页面
const toLogin = () => {
router.push({
path: "/login",
});
};
//错误信息处理
const errorHandle = (status, other) => {
switch (status) {
case 400:
console.log("信息校验失败");
break;
case 401:
toLogin();
console.log("认证失败");
break;
case 403:
toLogin();
console.log("token校验失败");
break;
case 404:
console.log("请求的资源不存在");
break;
default:
console.log(other);
break;
}
};
//添加请求拦截器
instance.interceptors.request.use(
function (config) {
if (config.method == "post") {//如果是post请求
config.data = qs.stringify(config.data);//则用qs把数据进行转换
}
return config;
},
function (error) {
return Promise.reject(error);
}
);
// 添加响应拦截器
instance.interceptors.response.use(
(res) => (res.status === 200 ? Promise.resolve(res) : Promise.reject(res)),
(error) => {
const { response } = error;
if (response) {
errorHandle(response.status, response.data.message);
return Promise.reject(response);
} else {
console.log("请检查您的网络");
}
}
);
export default instance
2.创建api文件夹,新建index,base,banner文件(js)
index
import banner from "./banner"
export default {
banner
}
base
const base={
baseUrl:"http://iwenwiki.com",
banner:"/api/blueberrypai/getIndexBanner.php"
}
export default base
banner
import base from "./base"
import axios from "../utils/request"
const banner={
bannerData(){
return axios.post(base.baseUrl+base.banner)
}
}
export default banner
使用
局部声明方式:
//先导入
import api from "../../api/index"
//在mounted中写入
api.banner.bannerData()
.then(res=>{
console.log(res.data);
})
全局声明方式为导入main.js中