关于axios:axios-response-data-返回空字符串

17次阅读

共计 1664 个字符,预计需要花费 5 分钟才能阅读完成。

最近对做 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: 200
statusText: ""

过后认为是 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: 200
statusText: ""

总结

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

正文完
 0