最近对做vue3我的项目时封装了一下axios作为网络申请工具,遇到了一个问题:发送post申请时,服务器返回的response data 为空字符串。然而 postman 测试能够失常返回数据(服务器是以json格局返回的数据)揣测是 axios 的配置出了问题。

查看config

过后是依照axios官网写的配置:

const config = {    timeout: options.timeout || 15000,    headers: options.headers,    url: '',    method: 'GET',    params: {},    data: {},    withCredentials: false,    paramsSerializer: function (params) {        return qs.stringify(params, {arrayFormat: 'brackets'})    },    transformResponse: [function (data) {        // Do whatever you want to transform the data        return qs.stringify(data);    }],}

根本是从官网抄了一些过去。

return new Promise((resolve, reject) => {    axios.request({        ...this.config    })        .then(response => {            console.log('response======', response)            resolve(response.data)        })        .catch(err => {            console.log(err)            reject(err.data)        })})

打印出的response如下:

config: {url: 'https://www.iic.top/api/login/login', method: 'post', data: '{"req":{"account":"userName123","password":"123456","captcha":"jms7"}}', headers: {…}, params: {…}, …}data: ""headers: {content-type: 'application/json; charset=utf-8'}request: XMLHttpRequest {onreadystatechange: null, readyState: 4, timeout: 10000, withCredentials: false, upload: XMLHttpRequestUpload, …}status: 200statusText: ""

过后认为是headers配置出了问题,特意给headers里边加了:

headers: {  'Accept': 'application/json',  'Content-Type': 'application/json'},

然而发现后果却和之前一样。

最终发现

是config中的transformResponse 这个办法把返回数据stringify导致data成了空字符串。

删除 transformResponse 办法后,返回后果失常:

config: {url: 'https://www.iicoom.top/api/guest/getGuestToken', method: 'post', headers: {…}, params: {…}, transformRequest: Array(1), …}data: {code: 40041, message: 'token有效'}headers: {content-type: 'application/json; charset=utf-8'}request: XMLHttpRequest {onreadystatechange: null, readyState: 4, timeout: 10000, withCredentials: false, upload: XMLHttpRequestUpload, …}status: 200statusText: ""

总结

配置信息不能轻易乱用,否则节约生命。