vue使用axios發送數據請求

本文章是基於vue-cli腳手架下開發javascript

1.安裝php

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

2.使用.在index.js中(渲染App組件的那個js文件)html

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

Vue.use(VueAxios, axios);

3.我的項目需求的一個小擴展.在我發起請求的時候.會須要去判斷域名.由於微信端開發中.微信要求是html5開頭的域名.因此要作一個請求攔截,並在判斷若是是html5下域名.訪問的接口須要加1層路徑.以保證請求正常.仍是在在index.js中(渲染App組件的那個js文件).而且已經use以後.加入代碼vue

//添加一個請求攔截器
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請求html5

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

5.post請求java

正常狀況下:ios

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

如下遍是坑的解決方法.問題都是由於Headers的Content-Type與服務器的接收的定義不同.致使post請求發過去以後.參數服務器都接收不到.spring

原帖鏈接: http://www.cnblogs.com/zhuzhenwei918/p/6869330.htmlvue-router

使用 application/x-www-urlencoded 形式的post請求:vue-cli

  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);
})
相關文章
相關標籤/搜索