vue使用axios发送数据请求

本文详细介绍了在Vue项目中如何使用Axios进行HTTP请求,包括安装、配置、请求拦截及get/post请求的具体实现。特别针对微信端开发中域名的要求,展示了如何通过请求拦截来动态修改请求地址。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

本文章是基于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

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值