vue使用axios发送数据请求

本文章是基于vue-cli脚手架下开发

1.安装

npm install axios --s
npm install vue-axios --s

2.使用.在index.js中(渲染App组件的那个js文件)

import VueAxios from 'vue-axios'
import VueRouter from 'vue-router'

Vue.use(VueAxios, axios);

3.个人项目需求的一个小扩展.在我发起请求的时候.会需要去判断域名.因为微信端开发中.微信要求是html5开头的域名.所以要做一个请求拦截,并在判断如果是html5下域名.访问的接口需要加1层路径.以保证请求正常.还是在在index.js中(渲染App组件的那个js文件).并且已经use之后.加入代码

//添加一个请求拦截器
Vue.prototype.$http.interceptors.request.use(function(config) {
    // 拦截请求修改地址
    if (/http://html5.a.com/ig.test(window.location.href) && !/http:///ig.test(config.url)) {
        config.url = 'http://html5.a.com/activity' + config.url
    } else if (/http://activity.a.com/ig.test(window.location.href) && !/http:///ig.test(config.url)) {
        config.url = 'http://activity.a.com' + config.url
    }
    return config;
}, function(err) {
    return Promise.reject(error);
});

4.get请求

this.$http.get('/user', {
    params: {
      ID: 12345
    }
  })
  .then(function (response) {
    console.log(response);
  })
  .catch(function (error) {
    console.log(error);
  });

5.post请求

正常情况下:

this.$http.post('/user', {
    ID: 12345
  })
  .then(function (response) {
    console.log(response);
  })
  .catch(function (error) {
    console.log(error);
  });

以下遍是坑的解决方法.问题都是因为Headers的Content-Type与服务器的接收的定义不一样.导致post请求发过去之后.参数服务器都接收不到.

原帖连接: http://www.cnblogs.com/zhuzhenwei918/p/6869330.html

使用 application/x-www-urlencoded 形式的post请求:

  import qs from 'qs'
  this.$http.post('/bbg/goods/get_goods_list_wechat', qs.stringify({"data": JSON.stringify({
"isSingle": 1,
    "sbid": 13729792,
    "catalog3": 45908012,
    "offset": 0,
    "pageSize": 25
  })}), {
    headers: {
      "BBG-Key": "ab9ef204-3253-49d4-b229-3cc2383480a6",
    }
  })
  .then(function (response) {
    // if (response.data.code == 626) {
      console.log(response);
    // }
  }).catch(function (error) {
    console.log(error);
  });

上边是一种解决方法.但是我的队友是java的springMVC服务器.so....无效啊.但是小伙伴说和php服务器通信的时候是有效的解决了post请求收不到参数的问题.所以参考以下连接文档.把参数包在URLSearchParams中.so....感觉与组织取得联系了...

原帖连接:http://www.jianshu.com/p/042632dec9fb

let param = new URLSearchParams();
param.append("activityId", "47");
param.append("type", "recv");
param.append("uid", this.uid);
this.$http.post('/married/getUserHomePage.do?',param).then((response) => {
   console.log(response)
}).catch((error) => {
   console.log(error);
})
原文地址:https://www.cnblogs.com/wwcherish/p/7384827.html