axios 备忘

axios 的引入:
axios 不是专门为 vue 设计的插件,所以不能使用 vue.use()。引入 axios 后可以通过修改原型链来调用:
//改写原型链
Vue. prototype . $http = axios

axios 的使用:
get:
// 为给定 ID 的 user 创建请求
axios.get( '/user?ID=12345' )
  .then( ( response ) => {
    console .log(response);
  })
  .catch( ( error ) => {
    console .log(error);
  });

// 可选地,上面的请求可以这样做
axios.get( '/user' , {
    params : {
      ID : 12345
    }
  })
  .then( ( response ) => {
    console .log(response);
  })
  .catch( ( error ) => {
    console .log(error);
  });
post:
axios.post( '/user' , {
    firstName : 'Fred' ,
    lastName : 'Flintstone'
  })
  .then( ( response ) => {
    console .log(response);
  })
  .catch( ( error ) => {
    console .log(error);
  });
All:
function getUserAccount() {
  return axios. get( ' /user/12345 ');
}

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

axios. all([ getUserAccount(), getUserPermissions()])
  . then( axios. spread( function ( account, permissions) {
    // Both requests are now complete
  }));


axios 和 spring boot 配合的注意事项:
有这种情况,axios 使用 post 传递参数的时候,后台接收不到,post 提交的数据放在 HTTP 协议的消息主体中,但没有规定编码方式,一般是四种:
1.application/x-www-form-urlencoded
最常见的, jQuery 的 ajax 就是这种。
2.multipart/form-data
也是常见的,广受支持的。
3.application/json
越来越多的开始使用这一种,告诉服务端消息主体是序列化后的 json 字符串,angular 中的和 axios 的 ajax 就是这种。
4.text/xml
也很广泛,不过用 xml 过于累赘,不推荐。

那么最简单的解决思路就是把 axios 的编码方式改成 jQuery 的那种就行了,axios 官方的解决办法:
Browser:
1.
var params = new URLSearchParams ();
params . append ( ' param1 ' , ' value1 ' );
params . append ( ' param2 ' , ' value2 ' );
axios . post ( ' /foo ' , params);
Note that  URLSearchParams  is not supported by all browsers (see  caniuse.com ), but there is a  polyfill  available (make sure to polyfill the global environment).
2.
var qs = require ( ' qs ' );
axios . post ( ' /foo ' , qs . stringify ({ ' bar ' : 123 }));

Node.js:
var querystring = require ( ' querystring ' );
axios . post ( ' http://something.com/ ' , querystring . stringify ({ foo : ' bar ' }));
You can also use the  qs  library.


axios 全局修改 post 编码方式:
在 main.js 中:一般不要全局设置,如果后台需要 x-www-form-urlencoded 格式的话就加个 qs
axios.defaults. headers .post[ 'Content-Type' ] = ' x-www-form-urlencoded ' ;
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值