Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

232
Visualizações
axios request cannot read property of undefined

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);
  }
about 4 years ago · Juan Pablo Isaza
2 Respostas
Responde à pergunta

0

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)
}
about 4 years ago · Juan Pablo Isaza Relatório

0

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));
      })
about 4 years ago · Juan Pablo Isaza Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda