1、代码如下
预期想通过调用登录接口,获取登录后的cookie,方便接下来的接口操作。但是刚开始在调用接口时,返回的responseHeader总是
与预期不符。通过抓包得知,调用登录接口返回的状态码是302,所以添加了axios.defaults.maxRedirects = 0 来禁止跟随重定向。
但是获取到的responseHeader依然与预期不符,最后分析得知,302会被axios当做error处理,通过error获取responseHeader与预期相符。
const axios = require("axios");
const querystring = require('querystring');
axios.defaults.maxRedirects = 0;
const data = {
user:'xxx',
password:'xxx',
toUrl=null
}
axios.post('https://www.test.net/user/login',qs.stringify(data))
.catch(function (error) {
console.log(error.response.headers)
})
2、另一种方法
var options = {
method:'post',
url: 'https://www.test.net/user/login',
data:
{ user: 'xxx',
password: 'xxx',
toUrl: null },
maxRedirects:0,
transformRequest: [function (data, headers) {
// 对 data 进行任意转换处理
return qs.stringify(data);
}]
};
axios.request(options).then(function (response) {
}).catch(function (error){
console.log(error.response.headers)
});
总结:axios将JavaScript对象序列化为JSON。 要以application / x-www-form-urlencoded格式发送数据,需要使用querystring转换