将以下代码放入 vue 项目结构中的 utils 文件夹 http.js 文件中:
'use strict'
import axios from 'axios'
import qs from 'qs'
//import storage from '@/utils/storage'
axios.defaults.withCredentials = true; //允许携带cookie
//请求拦截器:http请求发出前执行
axios.interceptors.request.use(config => {
config.headers['Content-Type'] = 'application/x-www-form-urlencoded; charset=UTF-8';
config.headers['Access-Control-Allow-Origin'] = '*';
//config.headers['UserToken'] = storage.get('token');//这里token用于权限验证
config.url = 'http://localhost:7777/api' + config.url;
//config.url = '/api' + config.url;//项目发布的时候,使用这个,将前端项目和后端api项目放于同一个站点,即可避免跨域问题
config.timeout = 50000;
return config;
}, error => {
return Promise.reject(error);
});
//响应拦截器:http请求返回后执行,根据实际情况是否使用
// axios.interceptors.response.use(response => {
// if (!response || response.status != 200) {
// //这里返回的数据结构可以根据实际情况自定义
// return {
// ExceptionCode: 0,
// Code: 100000,
// Message: '加载失败,请重试',
// Data: null,
// ServerTime: null
// }
// } else {
// if (response.data.Code == 200) {
// var t = typeof (response.data.Data);
// //这里是为了防止服务器返回了一个json字符串,前端不能直接使用,所以处理转换为json对象
// if (t == 'string' && response.data.Data.indexOf('{"') == 0) {
// return {
// ExceptionCode: response.data.ExceptionCode,
// Code: response.data.Code,
// Message: response.data.Message,
// Data: JSON.parse(response.data.Data),
// ServerTime: response.data.ServerTime
// };
// }
// return response.data;
// } else if (response.data.Code == 404) {
// return {
// ExceptionCode: 0,
// Code: 404,
// Message: '网络异常',
// Data: null,
// ServerTime: null
// }
// } else {
// response.data.Message = !response.data.Message || response.data.Message == null || response.data.Message == '' ? '加载失败,请重试' : response.data.Message;
// return response.data;
// }
// }
// }, error => {
// return Promise.resolve(error.response);
// });
export default {
post(url, data) {
return axios({
method: 'post',
url: url,
data: qs.stringify(data),
}).then(
(response) => {
if (response.status && response.status != 200) {
//这里返回的数据结构可以根据实际情况自定义
return {
ExceptionCode: 0,
Code: 100000,
Message: '加载失败,请重试',
Data: null,
ServerTime: null
}
}
return response.data;
}
)
},
get(url, data) {
return axios({
method: 'get',
url: url,
params: data
}).then(
(response) => {
if (response.status && response.status != 200) {
return {
ExceptionCode: 0,
Code: 100000,
Message: '加载失败,请重试',
Data: null,
ServerTime: null
}
}
return response.data;
}
)
}
}
用法如下:在需要使用http请求的组件中,先引入 http.js 文件,然后调用函数即可,示例:
<script>
import http from "@/utils/http";
import { async } from "q";
export default {
data() {
return {
tableData: [], //列表数据
};
},
mounted() {
this.getList();
},
methods: {
//获取列表数据
getList: async function() {
//这里需要使用 async 标记函数,使其支持异步,调用http请求数据时,使用 await 关键字等待数据返回
var result = await http.get("/modelweek/list", {
//这里写请求参数,传递一个对象即可
});
if (result && result.length && result.length > 0) {
this.tableData = result;
}
},
}
};
</script>