今天在使用axios进行参数获取时,始终获取不到,但是调用postman是正常的,所以初步估计是参数格式不正确,那么正确的应该怎么写呢?
一般按照正常的逻辑,我们在传递application/x-www-form-urlencoded时,参数应该这样写,但实际操作中发现一只获取不到参数。
axios.create({
baseURL: 'url',
timeout: 10000,
headers: { 'Content-Type': 'application/json' }
}).post('xxx/xxx/xxx',JSON.stringify({
name:'',
age:12
}),{
headers:{
'Content-Type': 'application/x-www-form-urlencoded'
}
}).then(function(response){
console.log(JSON.stringify(response));
}).catch(function(error){
console.log(error);
});
只需要添加两句代码,就可以正常获取啦.
var qs = require('qs');
然后把JSON.strinify改为qs.stringify就可以了。
var qs = require('qs');
axios.create({
baseURL: 'url',
timeout: 10000,
headers: { 'Content-Type': 'application/json' }
}).post('xxx/xxx/xxx',qs.stringify({
name:'',
age:12
}),{
headers:{
'Content-Type': 'application/x-www-form-urlencoded'
}
}).then(function(response){
console.log(JSON.stringify(response));
}).catch(function(error){
console.log(error);
});