从 Swapi 获取数据 API https://swapi.co/api/people/

Getting data from Swapi API https://swapi.co/api/people/

我想获取 https://swapi.co/api/people/ 所有名称和其他详细信息,但是当我使用 axios 调用获取数据时,我正在获取所有数据的 undefined 但如果想要一个名称,我我在控制台中收到 CORS 错误。

let button = document.querySelector("#button");
let name = document.querySelector("#displayDetail");

function getDetail(){
  var apiURL="https://swapi.co/api/people";
  axios.get(apiURL).then(function(response){    
    showDetail(response.data);
  });    
}

function showDetail(data){
  name.innerText=data.name;
}    

button.addEventListener('click',getDetail);

来自 https://swapi.co/api/people 的 JSON 数据没有 name 成员。相反,它有一个 results 成员,它是一个对象数组,每个对象都有一个 name 成员。

因此您需要遍历 data.results 数组以获取每个 name:

function getDetail() {
  var apiURL = "https://swapi.co/api/people";
  axios.get(apiURL).then(function(response) {
    showDetail(response.data);
  });
}

function showDetail(data) {
  for (i = 0; i < data.results.length; i++) {
    console.log(data.results[i].name);
  }
}
getDetail();
<script src="https://unpkg.com/axios/dist/axios.min.js"></script>

但请注意:API 端点对结果进行分页;所以要获取所有名称,请检查 data.next 以获取下一页的 URL,然后使用该 URL 发出新请求以获取下一组结果:

function getDetail(apiURL) {
  axios.get(apiURL).then(function(response) {
    showDetail(response.data);
  });
}

function showDetail(data) {
  for (i = 0; i < data.results.length; i++) {
    names = names + data.results[i].name + "\n";
    // name1.innerText = name1.innerText + "\n" + data.results[i].name;
  }
  if (data.next) {
    getDetail(data.next);
  } else {
    console.log(names); // name1.innerText = names;
  }
}
var names = "";
getDetail("https://swapi.co/api/people");
<script src="https://unpkg.com/axios/dist/axios.min.js"></script>

所有资源都支持过滤返回资源集的搜索参数。这使您可以进行如下查询:

https://swapi.co/api/people/?search=r2d2

要查看每个资源的搜索字段集,请查看各个资源文档。

试试这个 swapi.co/api/people/ 为。。改变 swapi.dev/api/people/