Axios
Axios 是一个基于
promise
的 HTTP 库,可以用在浏览器和 node.js 中。
踩坑
按照 axios 官网例子使用 axios.post 发起请求传递 json,后台接受到的数据为空
浏览器报错,然后使用 restlet
请求却可以正常返回数据
经过一波操作之后,最后发现是因为 axios 的默认提交方式是 application/json
这种
而后台接口的处理的是常见的 post 编码 application/x-www-form-urlencoded
这种
后台接收到的是经过序列化后的 json 字符串,所以没办法读取值出来
所以,问题找出来了,就可以解决问题了
解决
既然我们知道 axios post 方法默认使用 application/json
格式编码数据,
那么解决方案就有两种,一是后台改变接收参数的方法,另一种则是将 axios post 方法
的编码格式修改为 application/x-www-form-urlencoded
,这样就不需要后台做什么修改了。
第一种 后台解析
对接收到的参数进行解析,生成 json 对象
再对 json 对象进行处理
以 php 为例1
2
3$content = $GLOBALS["HTTP_RAW_POST_DATA"]; #获取原始数据
$re = json_decode($content); #生成json对象
......
这种方法最为简便,不过……如果接口已经写好了,
且接口很多,要改的话,还是要花点时间……
第二种 前端处理数据
在查阅文档之后,发现 axios 允许在向服务器发送前,修改请求数据
增加 transformRequest
方法参数:1
2
3
4
5
6
7
8
9
10
11
12
13
14{
url: '/user', // url 是用于请求的服务器 URL
method: 'post', // method 是创建请求时使用的方法,默认是 get
// `transformRequest` 允许在向服务器发送前,修改请求数据
// 只能用在 'PUT', 'POST' 和 'PATCH' 这几个请求方法
// 后面数组中的函数必须返回一个字符串,或 ArrayBuffer,或 Stream
transformRequest: [function (data) {
// 对 data 进行任意转换处理
return data;
}],
],
下面是处理代码:1
2
3
4
5
6
7
8
9
10{
//对提交的数据格式进行转换
transformRequest: [function (data) {
let ret = ''
for (let it in data) {
ret += encodeURIComponent(it) + '=' + encodeURIComponent(data[it]) + '&'
}
return ret
}],
}
完整代码是:1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18axios({
method: 'post',
url: 'https://api.github.com/user', #接口地址,仅参考
data: {
action: "getUserMessage",
userId: 100
},
//对提交的数据格式进行转换(post方法的坑)
transformRequest: [function (data) {
let ret = ''
for (let it in data) {
ret += encodeURIComponent(it) + '=' + encodeURIComponent(data[it]) + '&'
}
return ret
}]
}).then( response => {
console.log(response.data)
})
🎄然后就可以正常获取数据了~
最后,圣诞节快乐🎅~
附:
当参数是 JSON 字符串时,默认的 Content-Type
是 application/x-www-form-urlencoded
1
2
3
4
5
6
7
8
9
10axios.post('/user', JSON.stringify({
firstName: 'Fred',
lastName: 'Flintstone'
}))
.then(function (response) {
console.log(response);
})
.catch(function (error) {
console.log(error);
});
此时传递的参数是 Form Data
格式 key : value
1
{"firstName":"Fred","lastName":"Flintstone"}:
如上。这是一个无效的数据,key为 {"firstName":"Fred","lastName":"Flintstone"}
,value 为空。
🎅🎅🎅🎅🎅🎅🎅🎅🎅🎅🎅🎅🎅🎅🎅🎅🎅🎅🎅🎅🎅
🎄🎄🎄🎄🎄🎄🎄🎄🎄🎄🎄🎄🎄🎄🎄🎄🎄🎄🎄🎄🎄🎄🎄🎄🎄