1、cnpm i axios --save
2、新建js文件 src/utils/axois/index.js
import axios from 'axios';
import apiConfig from "./api.js";
import Vue from 'vue'
axios.defaults.baseURL = "/api";
let service = axios.create({
timeout: 60000,
headers: {
"Content-Type": "application/json",
"client": "pc_web"
},
contentType: "application/json;charset=utf-8",
dataType: "text",
});
// request 请求拦截器
service.interceptors.request.use(
config => {
return config;
},
error => {
Promise.reject(error)
}
)
// response 响应拦截器
service.interceptors.response.use(
result => {
const { config, data } = result;
try {
try {
return data;
} catch (e) {
console.error(config.url + "\r\nrequestBody:" + data + "\r\nresponseBody:" + result);
console.error(e);
return Promise.reject({ code: -1, message: "登录超时" })
}
} catch (e) {
console.log("解析数据错误");
console.error(config.url + "\r\n" + data);
console.error(e);
}
},
error => {
console.log('服务器异常,请联系管理员');
return Promise.reject(error.response) // 返回接口返回的错误信息
}
)
function appendUrlParams(url = '', params = {}) {
let str = String(url).trim();
if (Object.keys(params).length === 0) return str;
if (String(str).indexOf('?') === -1) str += '?';
else str += '&';
for (let key in params) {
str += `${key}=${params[key]}&`;
}
str = String(str).substr(0, str.length - 1);
return str;
}
const $fetch = async (apiName, params = {}, myloading, asyncType, config) => {
let newConfig = JSON.parse(JSON.stringify(apiConfigObj));
newConfig.asyncType = asyncType;
newConfig.myloading= myloading;
newConfig.data = params;
if (newConfig.method == 'get') { // get请求的话 往url追加参数
if (params) {
newConfig.url = appendUrlParams(newConfig.url, params)
}
}
let result = await service(newConfig).catch(err => {
return err;
})
return result;
}
export default $fetch;
3、新建js文件 src/utils/axois/api.js
let apiDomain = '/service/';
let brandApiurl = 'product-mall/';
let cartApiurl = '/cart/'
export default {
brandApi : {
brand: {
// 品牌列表
brandlist: {url: apiDomain + brandApiurl + 'brand/p_list', method: 'post'},
// 品牌详情
branddetails: {url: apiDomain + brandApiurl + 'brand/p_detail', method: 'post'},
}
},
}
4、test.vue demo演示调用方法
<template>
<section class="section_box" >
</section>
</template>
<script>
export default {
components: {},
data() {
return {
}
},
mounted() {
this.getClassify();
},
methods: {
// 获取筛选分类
getClassify() {
this.$fetch('brandApi.brand.brandlist', {}, '1111', '22222').then(res => {
}).catch(err => console.log("err",err))
},
}
}
</script>
完成了1-4的步骤可以完成一个基础的配置 但是接口没有配置映射,所以要接着有第5,添加接口代理
5、新建vue.config.js
let processEnvTarget = 'http://后端接口的域名地址';
console.log("processEnvTarget",processEnvTarget);
module.exports = {
outputDir: 'dist',
assetsDir: 'static',
devServer: {
port: 8080, // npm run serve 运行起来后的端口号
proxy: {
'/api': {
target: processEnvTarget,
changeOrigin: true,
ws: true,
pathRewrite: {
'^/api': ''
}
}
}
}
}