首页 > 解决方案 > Axios 调用后无法附加 div

问题描述

我查看了以前在这个论坛上提出的问题,但没有找到与这种特定情况相关的任何内容。我正在尝试根据从 Github 提取的数据创建用户卡。当我尝试将第一个子 div 附加到 HTML 中存在的父 div 时,我的代码会引发以下错误“TypeError:无法在 'Node' 上执行 'appendChild':参数 1 不是 'Node' 类型。” 问题是它绝对是一个节点。这是我的代码。

    //Axios call
    const info = axios.get(url).then(({ data }) => createCard(data));

    function createCard(gitHubData) {
  const cards = document.querySelector(".cards");

  //Creating the elements for the cards
  const card = document.createElement("div").classList.add("card");
  var img = document.createElement("img");
  const info = document.createElement("div").classList.add("card-info");
  var name = document.createElement("h3").classList.add("name");
  var username = document.createElement("p").classList.add("username");
  var location = document.createElement("p");
  var profile = document.createElement("p");
  var followers = document.createElement("p");
  var following = document.createElement("p");
  var bio = document.createElement("p");

  //Creating the nested layout of our elements
  cards.appendChild(card);  //code fails here
  card.appendChild(img);
  card.appendChild(info);
  info.appendChild(name);
  info.appendChild(username);
  info.appendChild(location);
  info.appendChild(profile);
  info.appendChild(followers);
  info.appendChild(following);
  info.appendChild(bio);

  //Assigning the cards to info collected from axios
  img.src = gitHubData.avatar_url;
  console.log(img.src);
  name = gitHubData.name; //If I use .innerHTML or .textContent returns 
                          //undefined
  console.log(name);
  username = gitHubData.login;
  location = gitHubData.location;
  profile = `Profile: ${gitHubData.html_url}`;
  followers = gitHubData.followers;
  following = gitHubData.following;
  bio = gitHubData.bio;

  return cards;
}

标签: javascriptapiaxios

解决方案


我仍然不确定为什么我的代码一开始就失败了,但是我晚上关闭了计算机,然后在早上再次尝试。正确的代码(我之前尝试失败的代码如下:

name.textContent = gitHubData.name;
username.textContent = gitHubData.login;
location.textContent = gitHubData.location;
profile.textContent = `Profile: ${gitHubData.html_url}`;
followers.textContent = gitHubData.followers;
following.textContent = gitHubData.following;
bio.textContent = gitHubData.bio;

推荐阅读