开发者问题收集

Axios:从 axios 帖子响应中获取数据时出现“未定义”值?

2019-11-27
286

我正在使用 axios 进行 Typescript 和 nodejs 的 API 测试。我到达一个端点并打印了这样的响应:

   then((response: { data: any; status: any }) => {
   ids = response.data;
   console.log(ids);

响应:

[ 

{ Id: '36185-test-157485' },

  { Id: '36185-test-157485' },

  { Id: '36185-test-675946' },

  { Id: '36185-test-157485' },

  { Id: '36185-test-764344' } 

]

我无法从此响应中获取第一个 ID。 我尝试过这个:

console.log(ids.id)

console.log(ids.id[0])

我是 axios 的新手。如果有人能建议最佳实践,我也很乐意使用它。

完整代码:

public listAllID's = async (idType: string, idOption: string) => {

    let ids:[
      {
        id: string [];
      }
    ];
    await axios({
      method: 'post',
      url: 'https://test-abc.com/api/v1/Allids',
      data: {
        "type": idType,
        "include": idOption
      },
      headers: {
        Authorization: 'Bearer ' + tokenId,
        'Content-Type': 'application/json'
      },
      json: true
    }).then((response: { data: any; status: any }) => {
     ids = response.data;
   console.log(ids);
      let statusCode = response.status;
      console.log(statusCode);
      expect(statusCode).to.be.equal(200);
    });
  }
}

这是通过此方法调用的:

Then(
  /^I list all ids of "([^"]*)" with other option  as "([^"]*)" from API$/, async (idType: string, idOption: string) => {
    await element.listAllIdsFromAPI(idType, idOption);
  });
1个回答

您可以通过这种方式访问​​第一个元素的 Id 字段:

console.log(ids.id[0]) // wrong - the array does not have a property 'id'

console.log(ids[0].Id) // correct - get the first element of the list and access it's 'Id' prop
Tsvetan Ganev
2019-11-27