简体   繁体   English

axios 请求无法读取未定义的属性

[英]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我正在尝试向服务器发出后端请求,并且我继续得到一个response.data返回,它是一些 HTML 作为一个字符串,上面写着TypeError: Cannot read property of undefined

I need to pass it a data object that looks like so:我需要将data object 传递给它,如下所示:

const data = {
  visitorId,
  patientId: oldPatientId,
  doctorId
}

and I need to pass it a json web token like so:我需要像这样传递一个 json web 令牌:

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.我担心我的 axios 代码设置不正确。 I am getting cannot read property undefined and a 500 statusCode error.我收到无法读取属性未定义和 500 statusCode错误。

I have consulted with the axios documentation to the best of my ability.我已尽我所能查阅 axios 文档。 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:我最了解的是 API 是前任工程师的代码,其设置如下所示:

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.您可以使用 async/await 或 promise,但不能在同一个调用中同时使用。 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 TLDR:确保您正确访问您的回复 object

I ran into this post and my issue ended up being because I was missing a '.data' on my object access我遇到了这篇文章,我的问题最终是因为我的 object 访问权限中缺少“.data”

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));
      })

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 Axios 请求失败并触发无法读取未定义的属性“地图” - Axios request fails which fires Cannot read property 'map' of undefined FourSquare Axios请求-ReactJs-无法读取未定义的属性“ map” - FourSquare Axios Request - ReactJs - Cannot read property 'map' of undefined 带有axios的reactjs“无法读取未定义的属性&#39;map&#39;” - reactjs with axios “Cannot read property 'map' of undefined`” Axios ReactJS - 无法读取undefined的属性&#39;setState&#39; - Axios ReactJS - Cannot read property 'setState' of undefined 无法读取 axios 包装器未定义的属性“then” - Cannot read property 'then' of undefined for axios wrapper 无法读取未定义的Axios,Vuex的属性“名称” - Cannot read property 'name' of undefined Axios, Vuex 无法读取未定义的属性 'xxx' - 使用 axios - Cannot read property 'xxx' of undefined - using axios 无法读取未定义的属性“请求” - Cannot read property 'request' of undefined 反应 js Axios 请求失败:TypeError:无法读取未定义的属性“令牌”? - react js Axios request failed: TypeError: Cannot read property 'token' of undefined? ReactJS 使用离子未捕获类型错误:无法从 axios 请求中读取未定义的属性“映射” - ReactJS using Ionic Uncaught TypeError: Cannot read property 'map' of undefined from axios request
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM