axios 数据请求

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); 
  }); 

 

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值