I am trying to make a backend request to a server and I continue to get a response.data back that is some HTML as a string that says TypeError: Cannot read property of undefined
I need to pass it a data object that looks like so:
const data = {
visitorId,
patientId: oldPatientId,
doctorId
}
and I need to pass it a json web token like so:
const userJWT = jwt.sign(
{
_id: visitorId,
refreshCount: 0
},
this.localConfig.spyrt.jwtSecret
)
and headers that look like so:
const headers = {
'Content-Type': 'application/json',
'Authorization': `Bearer ${userJWT}`
}
I am doing this inside an asynchronous method like so:
async jwtTest(visitorId: number, oldPatientId: number, doctorId: number): Promise<void> {
const data = {
visitorId,
patientId: oldPatientId,
doctorId
}
const userJWT = jwt.sign(
{
_id: visitorId,
refreshCount: 0
},
this.localConfig.spyrt.jwtSecret
)
const headers = {
'Content-Type': 'application/json',
'Authorization': `Bearer ${userJWT}`
}
if (this.localConfig.spyrt.active) {
const dto = await axios.post(visitURL, data, {headers}).then((response) => {
console.log(response.data);
}).catch((error) => {
console.log(error);
});
}
}
I am concerned that my axios code is not set up correctly. I am getting cannot read property undefined and a 500 statusCode error.
I have consulted with the axios documentation to the best of my ability. Does anyone see anything wrong with my setup?
I tried this implementation:
if (this.localConfig.spyrt.active) {
await axios.post(visitURL, data, {headers}).then(function(response) {
console.log(JSON.stringify(response.data));
}).catch(function(error) {
console.log(error);
})
}
and with this one I get the exact same response.
The closest I have to understanding that API is the previous engineer's code whose setup looked like this:
try {
let response = await fetch(visitURL, {
method: 'POST',
headers: {
'Content-Type': 'application/json',
'Authorization': 'Bearer ' + acct.jwt
},
body: JSON.stringify(visit)
});
if (response.ok) {
let result = await response.json();
callback(result);
} else {
throw new Error('Model: createVisit failed!');
}
} catch (error) {
console.log(error);
}
You would either use async/await or promise, but not both in the same invocation. Quickest fix would be:
try {
const dto = await axios.post(visitURL, data, {headers})
const data = dto.data
console.log(data)
} catch (err) {
console.log(error)
}
TLDR: make sure you're properly accessing your response object
I ran into this post and my issue ended up being because I was missing a '.data' on my object access
I had this (wrong)
axios
.post(`${process.env.VUE_APP_ROOT_URL}/score/`, {'day':today})
.then(response => {
response.categories.forEach(element => console.log(element.score));
})
vs the correct:
axios
.post(`${process.env.VUE_APP_ROOT_URL}/score/`, {'day':today})
.then(response => {
response.data.categories.forEach(element => console.log(element.score));
})