目录结构:
安装axios
cnpm i axios -D
axios.js 文件
import axios from "axios";
import qs from "qs"; //处理参数
import { Message } from 'element-ui';
//添加请求拦截器
axios.interceptors.request.use(
config => {
// try {
// if (sessionStorage.token) {
// // 设置统一的请求header
// config.headers.token = sessionStorage.token //请求头携带token
// }
// } catch (error) {
// console.log(error)
// }
return config;
},
error => {
return Promise.reject(error);
}
);
//添加响应拦截器
axios.interceptors.response.use(
response => { //逻辑处理
return response;
},
error => {
return Promise.resolve(error.response);
}
);
// axios.defaults.baseURL = "xxxxxxxxxxxxxxxxxxxxxx"; // 请求地址统一配置到vue.config.vue中
axios.defaults.headers.post["Content-Type"] = "application/json";
// axios.defaults.headers.post["X-Requested-With"] = "XMLHttpRequest";
axios.defaults.timeout = 20000; //设置请求超时时间
function checkStatus(response) {
return new Promise((resolve, reject) => {
if (response && (response.status === 200 || response.status === 304 || response.status === 400)) {
try {
resolve(response.data);
} catch (e) {
//抛出异常
console.log(e)
}
} else {
try {
Message({
type: 'error',
showClose: true,
message: '网络异常,请检查网络连接是否正常!'
})
} catch (e) {
//抛出异常
console.log(e)
}
}
});
}
export default {
post(url, params) {
return axios({
method: "post",
url,
data: params
}).then(response => {
return checkStatus(response);
});
},
get(url, params) {
params = qs.stringify(params);
return axios({
method: "get",
url,
params
}).then(response => {
return checkStatus(response);
});
}
};
require.js
import Ajax from './axios'
export async function homeBanner() {
return await Ajax.get("/home/banner")
}
export async function projectlist(data) {
return await Ajax.post("/project/list",data)
}
// 在vue文件中使用
import { projectlist, homeBanner } from '@/api/request.js'
async request() {
let res = await projectlist({date: '1111'})
if(res.code === 0){
}else{
}
}
vue.config.vue 文件
module.exports = {
// 关闭eslint
lintOnSave: false,
// 关闭eslint
devServer: {
port: 8386,
https: false,
hotOnly: true, //是否开启热更新
open: true, //配置自动启动浏览器
proxy: {
"/": {
target: "https://fomixxxx.xxxxx168.com/", // 测试
ws: true,//是否代理websockets
changeOrigin: true , // 设置同源 默认false,是否需要改变原始主机头为目标URL
pathRewrite: {
"^/": "/"
}
}
}
}
}