vue --- axios

1.axios

先说一下axios吧,官方说法Axios 是一个基于 promise 的 HTTP 库,可以用在浏览器和 node.js 中,特点是

  • 从浏览器中创建 XMLHttpRequests
  • 从 node.js 创建 http 请求
  • 支持 Promise API
  • 拦截请求和响应
  • 转换请求数据和响应数据
  • 取消请求
  • 自动转换 JSON 数据
  • 客户端支持防御 XSRF

用法有很多种

axios.request(config);
axios.get(url[, config]);
axios.delete(url[, config]);
axios.head(url[, config]);
axios.post(url[, data[, config]]);
axios.put(url[, data[, config]]);
axios.patch(url[, data[, config]]);

2.vue中安装使用

npm安装

npm install axios -S

组件中引入

import axios from 'axios';

基本用法:get请求的两种方法

// 传统写法
axios.get('/user?ID=12345')
  .then(function (response) {
    console.log(response);
  })
  .catch(function (error) {
    console.log(error);
  });

// 可以这样写
axios.get('/user', {
    params: {
      ID: 12345
    }
  })
  .then(function (response) {
    console.log(response);
  })
  .catch(function (error) {
    console.log(error);
  });

//还可以这样写axios(config)
axios({
    methods: 'get',
    url: '/user',
    params: {
        ID: '1234'
    }
})
.then( (response) => {
    console.log(response);
})
.catch( (error) => {
    console.log(error);
});

基本用法:post请求

//传统写法
axios.post('/user', {
    firstName: 'Fred',
    lastName: 'Flintstone'
  })
  .then(function (response) {
    console.log(response);
  })
  .catch(function (error) {
    console.log(error);
  });

//配置写法
axios({
    method:"POST",
    url:'/user/12345',
    data:{
        firstName:"Fred",
        lastName:"Flintstone"
    }
}).then(function (response) {
    console.log(response);
  })
  .catch(function (error) {
    console.log(error);
  });;

 同时发起多个请求

function getUserAccount() {
  return axios.get('/user/12345');
}

function getUserPermissions() {
  return axios.get('/user/12345/permissions');
}

axios.all([getUserAccount(), getUserPermissions()])
  .then(axios.spread(function (acct, perms) {
    //当这两个请求都完成的时候会触发这个函数,两个参数分别代表返回的结果
}));

因为配置写法的get和post比较相似,仅仅是参数的键名不一致,所以我简单地封装了一下,下面是一个我自己封装的方法

import axios from 'axios'

let axiosRequest = function(method,url,Data,callBack){
  let data = method.toLocaleLowerCase() === 'get' ? 'params' : 'data';
  let option = {
      method: method,
      url: url,
      [data]: Data
    }
  let Axios = function(){
    axios(option).then(function(res){
      Promise.resolve(callBack(res.data))
    }).catch(function(err){
      throw Promise.reject((err))
    })
  }
  if(!callBack){ //get请求没有请求参数的情况
    callBack = Data;
    delete option.data;
    Axios()
  }else{
    Axios()
  }
}

export default axiosRequest;

不过axios post传参有坑,刚开始我是这样写的

axios.post(_this.url+"/bigdata/bhall/ActiveInfo/getActivesByPersonId", {
		'hId':this.$route.query.hId,
		'personId':this.$route.query.id,
		'date':new Date().toLocaleDateString()
	}
).then(function(data){
	_this.MarketingInformation = data.data;
}) .catch(function (error) {
    throw (error);
  });

后台收不到参数,后来更改成这样

axios({
    method:"POST",
    url:_this.url+"/bigdata/bhall/ActiveInfo/getActivesByPersonId",
    data:{
        'hId':this.$route.query.hId,
	'personId':this.$route.query.id,
	'date':new Date().toLocaleDateString()
    }
}).then(function (response) {
    console.log(response);
  })
  .catch(function (error) {
    throw (error);
  });

后台还是收不到,emmmm~,后来再网上查了好多资料,发现需要把Content-Type为application/x-www-form-urlencoded,使用原生ajax、axios请求时,如果不显示的设置Content-Type,那么默认是text/plain,服务器识别不了,只能通过获取原始数据流的方式来进行解析请求数据;

后来找到了解决方法,有两种:

1.创建new URLSearchParams()

let parames = new URLSearchParams();
params.append('hId',this.$route.query.hId);
params.append('personId',this.$route.query.id);
params.append('date',new Date().toLocaleDateString());

2.使用qs

npm下载qs

 npm i qs --save

组件中引入

import qs from 'qs';
Vue.prototype.$qs = qs

封装方法

	const getData = (type,url,data) => {
		return axios({
			method:type,
			url:url,
			data:qs.stringify(data),//data为一个对象
			headers:{'Content-Type':'application/x-www-form-urlencoded'}//设置类型
		})
		.then((res) => res.data)
		.catch((err) => {
			console.log('网络异常,请重试')
		})
	}

下面是调用方式

//_this.closeinfo数据结构
_this.closeinfo = {
	'hId':this.$route.query.hId,
	'personId':this.$route.query.id,
	'date':new Date().toLocaleDateString()
}

//调用方法
getData('post',_this.url+"/bigdata/bhall/ActiveInfo/activeInfoSave",_this.closeinfo)

两种方法均可使用

推荐一篇文章,axios post提交数据的三种请求方法

https://segmentfault.com/a/1190000015261229

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值