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 编码方式:
在 main.js 中:一般不要全局设置,如果后台需要 x-www-form-urlencoded 格式的话就加个 qs
axios.defaults.
headers
.post[
'Content-Type'
] =
'
x-www-form-urlencoded
'
;