【问题标题】:axios request cannot read property of undefinedaxios 请求无法读取未定义的属性
【发布时间】:2021-12-10 23:41:05
【问题描述】:

我正在尝试向服务器发出后端请求,并且我继续得到一个 response.data 返回,它是一些 HTML 字符串,上面写着 TypeError: Cannot read property of undefined

我需要向它传递一个看起来像这样的data 对象:

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

我需要像这样传递一个 json 网络令牌:

const userJWT = jwt.sign(
  {
    _id: visitorId,
    refreshCount: 0
  },
  this.localConfig.spyrt.jwtSecret
)

以及看起来像这样的标题:

const headers = {
  'Content-Type': 'application/json',
  'Authorization': `Bearer ${userJWT}`
}

我在这样的异步方法中执行此操作:

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

      

我担心我的 axios 代码设置不正确。我收到无法读取未定义的属性和 500 statusCode 错误。

我已尽我所能查阅了 axios 文档。有人发现我的设置有什么问题吗?

我试过这个实现:

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

有了这个,我得到了完全相同的响应。

最接近我理解的 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);
  }

【问题讨论】:

  • 具体是什么未定义,在哪里?给minimal reproducible example。如果是dto,那么请注意,.then(() =&gt; { console.log("something") }) 不仅意味着你现在有一个未定义的承诺,它后面的.then(() =&gt; {}) 无论如何都会这样做。
  • 从描述看来,服务器端发生了错误,而不是客户端
  • @David,这是否意味着我的实现没有问题?
  • @Daniel:也许吧?测试和调试可以证实这一点。但是,您所做的任何此类测试和调试都应该非常明确地说明观察到的确切错误以及观察到的位置。这个错误信息是从服务器返回的吗?
  • 同样,.then 在它之前记录,然后什么也不返回, 导致整个承诺链解决未定义。但如果该消息在 response body 中,那么您处理响应的方式就不是那么重要了 - 500 表示服务器端错误,并且您没有向我们展示任何有关 API 实现的信息。你是否提出了错误的要求?也许吧,但即使是这样,也很难说哪个是正确的。

标签: javascript typescript axios


【解决方案1】:

您可以使用 async/await 或 Promise,但不能在同一个调用中同时使用。最快的解决方法是:

try {
  const dto = await axios.post(visitURL, data, {headers})
  const data = dto.data
  console.log(data)
} catch (err) {
  console.log(error)
}

【讨论】:

  • 它们完全可以互操作,但 OP 似乎使用不正确。
  • 不在同一个调用中
  • 是在同一个调用中。例如。 const data = await fetch(url).then(res =&gt; res.json()) 可以正常工作(尽管我同意这样混合它们可能会令人困惑)。问题是(也许)OP 正在链接.then 回调不返回任何东西
  • 好的,我承认我不知道或见过
  • @KevinLe-Khnle,我的实施结果相同。
猜你喜欢
  • 2018-11-14
  • 2022-10-19
  • 2020-11-28
  • 2021-02-18
  • 2021-08-23
  • 2020-07-07
  • 2021-09-10
  • 2021-11-14
  • 2017-04-06
相关资源
最近更新 更多