Problem: console.log(res.data)
gives a different result from console.log(JSON.parse(res.request.response))
.
I am making a post request to an internal API from my Next.js app. It is a request to a REST endpoint that returns a list object. The data should look like the following:
[
{
"views": [ { "data1": 1 ...}, ...],
"otherViews": [ {"data2": 1, ...}, ...],
},
...
]
I am accessing the data from this request in the typical then/catch
format. So
let internalServerResponse = axios.post(endpoint, body, config)
return internalServerResponse
.then(res => {
let errors = null;
let data = null;
if (res.data.errors) {
errors = res.data.errors;
} else {
data = res.data
}
return {
errors: errors,
data: data
}
} )
.catch(err => {
return {
errors: err,
data: null
}
})
The issue arises where the views
list always returns an empty list, while the otherViews
list seems to be unaffected.
{
"identifier": "...",
"views": [],
"otherViews": [
{
"field1": "...",
"field2": "...",
"field3": "..."
},
...
]
}
Looking at the res.request.response
from the server, I see that the views
list is not actually empty (as intended), and that the format the objects in the views list is similar to that of the otherViews
list. The returned response (res.request.response
) is valid JSON.
Console log output of JSON.parse(res.request.response)
:
{
"identifier": "...",
"views": [
{
"field1": "...",
"field2": "...",
"field3": "..."
},
...
],
"otherViews": [
{
"field1": "...",
"field2": "...",
"field3": "..."
},
...
]
}
What I Tried
To debug, I tried:
- printing
res.data
which gives the missing views list - printing
JSON.parse(res.request.response)
which gives the correct object - setting my
data = JSON.parse(res.request.response)
which still somehow gives the missing view list
I am completely stumped. I have two questions:
- Why is res.data and JSON.parse(res.request.response) different?
- How on earth is the value changing when I assign it to a variable?