Axios:从axios响应后获取数据时会出现“未定义”值吗?

时间:2019-11-27 13:05:02

标签: typescript axios

我正在使用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 个答案:

答案 0 :(得分: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