axios post json_vue进行post和get请求

参考文档:https://www.jb51.net/article/125717.htm

基本使用方法:

get请求:

// Make a request for a user with a given IDaxios.get('/user?ID=12345') .then(function (response) {  console.log(response); }) .catch(function (error) {  console.log(error); }); // Optionally the request above could also be done asaxios.get('/user', {  params: {   ID: 12345  } }) .then(function (response) {  console.log(response); }) .catch(function (error) {  console.log(error); });

Post请求:

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

简单示例:

// 在进行 post 和 get 请求的时候,使用 axios 进行访问// 进行 get 请求axios.get(url).then(function (response){    console.log(response);}).catch(function(error){    console.log(error);});// 进行post 请求            axios.post(url,{firstName:'Fred',lastName:'Flintstone'}).then(function (response) {    console.log(response);}).catch(function (error) {    console.log(error);});

这样发送请求,虽然是可以发送,但是携带的参数,是一个json字符串,会出现问题。所以我们在用post发送请求的时候,需要这样:

axios({      method:'post',      url:url,      data:{title:this.title,content:this.content},      headers:{'Content-Type': 'application/x-www-form-urlencoded'},      transformRequest: function(obj) {          var str = [];          for(var p in obj){              str.push(encodeURIComponent(p) + "=" + encodeURIComponent(obj[p]));          }          return str.join("&");      }  }).then((res)=>{    console.log(res.data);});

2b2b555c85ae640d78471643e3cc4f13.png

上面这种只能提交一些简单的数据,对于复杂的数据,可以考虑使用 QS 对数据进行处理。

使用方法,如果找不到QS文件,可以只用 npm 安装:

npm install qs

下载这个文件之后,使用 script 标签正常引入即可。

使用方法:

var formData = Qs.stringify({imgIds: [48,49],});
axios.post(url,Qs.stringify(this.formData)).then(function (response) {    console.log(response);}).catch(function (error) {    console.log(error);});

或者是:

axios({    method: 'post',    url:url,    data:Qs.stringify(this.formData),}).then((res)=>{    console.log(res);});
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值