设置API的日期和文本数据格式



我正在使用Github API,并显示来自用户的数据。当显示日期时,我希望它只有日期user.created_at和DD/MM/YY,而不是整个小时。此外,当用户没有传记user.bio时,数据显示为null,我希望它显示文本"用户没有传记"。我还没有想出同时做这两件事的方法,所以如果你能帮助我,我将非常感谢

下面的代码:

const APIURL = 'https://api.github.com/users/'
const main = document.getElementById('main')
const form = document.getElementById('form')
const search = document.getElementById('search')
async function getUser(username){
try{
const { data } = await axios(APIURL + username)
createUserCard(data)
getRepos(username)
}catch (err){
if(err.response.status == 404){
createErrorCard('No profile with this Username')
}
}
}
async function getRepos(username){
try{
const { data } = await axios(APIURL + username + '/repos?sort=created')
addReposToCard(data)
}catch (err){
createErrorCard('Problem Fetching Repos')
}
}
function createUserCard(user){
const cardHTML = `
<div class="card">
<div>
<img src="${user.avatar_url}" alt="${user.name}" class="avatar">
</div>
<div class="user-info">
<div class="header">
<h2>${user.name}</h2>
<p class="date">Joined ${user.created_at}</p>
</div>
<p>@${user.login}</p>
<p>${user.bio}</p>


<ul>
<div class="list">
<li>${user.followers} </li>
<li>${user.following} </li>
<li>${user.public_repos} </li>

</div>
<div class="list-names">
<strong>Followers</strong>

<strong>Following</strong>

<strong>Repos</strong>


</div>



</ul>

<div class="additional-data">
<p class="location"><img src="./img/location.svg" alt="Location" class="img" />  ${user.location} </p>
<a href=${user.html_url} target="_blank"><img src="./img/link.svg" alt="Link" class="img" />${user.html_url}</a>
</div>
<div id="repos"></div>
</div>
</div>`
main.innerHTML = cardHTML
}

function createErrorCard(msg){
const cardHTML = `
<div class="card">
<h1>${msg}</h1>
</div>
`
main.innerHTML = cardHTML
}

function addReposToCard(repos){
const reposEl = document.getElementById('repos')
repos
.slice(0, 5)
.forEach(repo => {
const repoEl = document.createElement('a')
repoEl.classList.add('repo')
repoEl.href = repo.html_url
repoEl.target = '_black'
repoEl.innerText = repo.name
reposEl.appendChild(repoEl)
})
}
form.addEventListener('submit', (e) => {
e.preventDefault()
const user = search.value
if(user){
getUser(user)
search.value = ''
}
})
  1. 在user.bio的情况下,您可以使用三元运算符:

    (conditional)?value when conditional true: value when conditional false
    

    例如:

    ${(user.bio!="null")?user.bio:"The user has no bio"}
    

    ${(user.bio!=null)?user.bio:"The user has no bio"}
    
  2. 在日期的情况下,github帮助我们提供一个格式化的字符串,我们可以使用new Date()将其转换为日期,并使用Date.prototype.toLocaleString()进行格式化

    ${(new Date(user.created_at)).toLocaleDateString()}
    

    在这种情况下,不需要将参数传递给toLocaleDateString(),但我鼓励您在这里阅读

最新更新