1、安装axios和qs
npm install axios
npm install qs
2、在vue的项目入口文件main.js中,引入我们所需要axios(已经封装好的ajax,也可以用fetch,但是兼容性不如axios好),同时需要引入qs模块(我们在做post请求的时候需要用到)
import axios from 'axios'
import qs from 'qs'
Vue.prototype.$http = axios;axios.defaults.baseURL = 'http://192.168.1.116';
//
//添加请求拦截器
axios.interceptors.request.use(function (config) {
config.headers['Content-Type'] = 'application/x-www-form-urlencoded'
if(config.method === 'post') { // post请求时,处理数据
config.data = qs.stringify( {
...config.data //后台数据接收这块需要以表单形式提交数据,而axios中post默认的提交是json数据,所以这里选用qs模块来处理数据,也有其他处理方式,但个人觉得这个方式最简单好用
})
}
return config;
}, function (error) {
loadinginstace.close()
return Promise.reject(error);
})
//添加响应拦截器
axios.interceptors.response.use(function(response){
return response;
},function(error){
return Promise.reject(error);
});
3、在vue文件中的使用方法,get与post方法均可~
// 以下为请求测试环境的get接口测试
this.$http.get(this.HOST + '/init',{
params:{
"cityCode":"010"
}
}).then((response) => {
console.log("get:"+response.data);
});
// 以下为请求测试环境的post接口测试 处理数据这块儿,试用过很多种方法,没效果…… 例如 用字符串拼接,以及用params.append,亲测数据丢失,嗯,还是乖乖的用qs吧……
let url = this.HOST + '/mod';
let data = {
"savestatus":1,"favType":1,"tag":"danny"
};
this.$http.post(url,data).then((response) => {
console.log("post:"+response.data);
})
// 以下为请求本地json文件的方法,本地json文件必须放在最外层的static/xxx.json
this.$http.get("../static/datagrid_data1.json").then(response => {
console.log("static:"+response.data);
});