Recently, I encapsulated axios as a network request tool when I was working on a vue3 project. I encountered a problem: when sending a post request, the response data returned by the server was an empty string. However, the postman test can return data normally (the server returns the data in json format). It is speculated that there is a problem with the configuration of axios.
view config
At that time, it was according to the configuration written on the axios official website:
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);
}],
}
Basically copied some from the official website.
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)
})
})
The printed response is as follows:
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: ""
At that time, I thought that there was a problem with the headers configuration, so I added the following to the headers:
headers: {
'Accept': 'application/json',
'Content-Type': 'application/json'
},
But the results were the same as before.
finally found
It is the transformResponse method in config that stringify the returned data, causing the data to become an empty string.
After deleting the transformResponse method, the returned result is normal:
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: ""
Summarize
Configuration information cannot be used indiscriminately, otherwise life is wasted. 📚
**粗体** _斜体_ [链接](http://example.com) `代码` - 列表 > 引用
。你还可以使用@
来通知其他用户。