Handling Response Data
# Handling Response Data
# Requirements Analysis
When we don't set responseType, if the server returns string data, we can try to convert it to a JSON object. For example:
data: "{"a":1,"b":2}"
1
We convert it to:
data: {
a: 1,
b: 2
}
1
2
3
4
2
3
4
# Implementing and Applying the transformResponse Function
Based on the requirements, we need to implement a transformResponse utility function.
helpers/data.ts:
export function transformResponse(data: any): any {
if (typeof data === 'string') {
try {
data = JSON.parse(data)
} catch (e) {
// do nothing
}
}
return data
}
1
2
3
4
5
6
7
8
9
10
2
3
4
5
6
7
8
9
10
index.ts:
function axios(config: AxiosRequestConfig): AxiosPromise {
processConfig(config)
return xhr(config).then((res) => {
return transformResponseData(res)
})
}
function transformResponseData(res: AxiosResponse): AxiosResponse {
res.data = transformResponse(res.data)
return res
}
1
2
3
4
5
6
7
8
9
10
11
2
3
4
5
6
7
8
9
10
11
Looking at the demo again, we can see that the response data field has been parsed from a string to a JSON object structure.
With that, the core features of ts-axios are now implemented. However, up to this point we've only handled the happy path. The next chapter will address various error scenarios.
Edit (opens new window)
Last Updated: 2026/03/21, 12:14:36