Я построил этот поисковый индуст для покемонов для freecodecamp.org, и он прошел тесты, так что я не пытаюсь улучшить его, но я не знаю всех покемонов, поэтому я добавил API под названием poke.api, я могу получить к нему доступ от моего браузера, но он выбрасывает ошибку, когда я ищу Pikachu.const searchInput = document.getElementById('search-input');
const searchButton = document.getElementById('search-button');
const pokemonInfo = document.getElementById('pokemon-info'); // Use this for appending elements
const pokemonName = document.getElementById('pokemon-name');
const pokemonId = document.getElementById('pokemon-id');
const weight = document.getElementById('weight');
const height = document.getElementById('height');
const types = document.getElementById('types');
const hp = document.getElementById('hp');
const attack = document.getElementById('attack');
const defense = document.getElementById('defense');
const specialAttack = document.getElementById('special-attack');
const specialDefense = document.getElementById('special-defense');
const speed = document.getElementById('speed');
const sprite = document.getElementById('sprite');
searchButton.addEventListener('click', async () => {
const searchTerm = searchInput.value.toLowerCase();
clearPokemonInfo(); // Clear previous data before searching
const loadingMessage = document.createElement('p');
loadingMessage.textContent = 'Loading...';
pokemonInfo.appendChild(loadingMessage);
try {
const response = await fetch(`https://pokeapi.co/api/v2/pokemon/${searchTerm}`);
if (!response.ok) {
throw new Error(`Pokémon not found (HTTP status: ${response.status})`);
}
const pokemonData = await response.json();
validatePokemonData(pokemonData, searchTerm);
await displayPokemonInfo(pokemonData); //Await the display
} catch (error) {
const errorMessage = document.createElement('p');
errorMessage.textContent = `Error: ${error.message}`;
errorMessage.style.color = 'red';
pokemonInfo.appendChild(errorMessage);
} finally {
pokemonInfo.removeChild(loadingMessage); //Remove loading message
}
});
async function displayPokemonInfo(pokemonData) {
pokemonName.textContent = pokemonData.name.toUpperCase();
pokemonId.textContent = pokemonData.id;
weight.textContent = pokemonData.weight;
height.textContent = pokemonData.height;
hp.textContent = pokemonData.stats.find(stat => stat.stat.name === 'hp').base_stat;
attack.textContent = pokemonData.stats.find(stat => stat.stat.name === 'attack').base_stat;
defense.textContent = pokemonData.stats.find(stat => stat.stat.name === 'defense').base_stat;
specialAttack.textContent = pokemonData.stats.find(stat => stat.stat.name === 'special-attack').base_stat;
specialDefense.textContent = pokemonData.stats.find(stat => stat.stat.name === 'special-defense').base_stat;
speed.textContent = pokemonData.stats.find(stat => stat.stat.name === 'speed').base_stat;
sprite.src = pokemonData.sprites.front_default;
//Improved type display
const typesElement = document.createElement('p');
typesElement.innerHTML = 'Types: ';
pokemonData.types.forEach(type => {
const typeIcon = document.createElement('img');
typeIcon.src = `type-icons/${type.type.name}.png`; //Requires type-icons folder with images
typeIcon.alt = type.type.name;
typeIcon.width = '20';
typeIcon.height = '20';
typesElement.appendChild(typeIcon);
typesElement.appendChild(document.createTextNode(type.type.name.toUpperCase() + ' '));
});
pokemonInfo.appendChild(typesElement);
// Fetch and display abilities - more robust handling of errors and multiple abilities
const abilities = await Promise.all(pokemonData.abilities.map(async ability => {
const response = await fetch(ability.url);
if (!response.ok) {
console.error(`Error fetching ability: ${ability.url}`, response.status);
return null; //Handle failed ability fetch gracefully
}
const abilityData = await response.json();
return abilityData.name; // Return just the name of the ability
}));
const abilitiesList = abilities.filter(a => a !== null).join(', '); //Filter out null values before joining.
const abilitiesElement = document.createElement('p');
abilitiesElement.innerHTML = `Abilities: ${abilitiesList}`;
pokemonInfo.appendChild(abilitiesElement);
}
function validatePokemonData(pokemonData, searchTerm) {
// Add your validation logic here based on the test cases. For example:
if (searchTerm === 'pikachu') {
// ... (Your Pikachu validation code) ...
} else if (searchTerm === '94') {
// ... (Your Gengar validation code) ...
}
//Add other validations as needed.
}
function clearPokemonInfo() {
while (pokemonInfo.firstChild) { //Completely clear the pokemonInfo div.
pokemonInfo.removeChild(pokemonInfo.firstChild);
}
}
< /code>
Я попытался искать Пикачу на самом API, и он работает, так что на моем конце не так.>
Подробнее здесь: https://stackoverflow.com/questions/795 ... or-but-why
Мой Pokeapi получает ошибку, но почему? ⇐ Javascript
Форум по Javascript
1741738412
Anonymous
Я построил этот поисковый индуст для покемонов для freecodecamp.org, и он прошел тесты, так что я не пытаюсь улучшить его, но я не знаю всех покемонов, поэтому я добавил API под названием poke.api, я могу получить к нему доступ от моего браузера, но он выбрасывает ошибку, когда я ищу Pikachu.const searchInput = document.getElementById('search-input');
const searchButton = document.getElementById('search-button');
const pokemonInfo = document.getElementById('pokemon-info'); // Use this for appending elements
const pokemonName = document.getElementById('pokemon-name');
const pokemonId = document.getElementById('pokemon-id');
const weight = document.getElementById('weight');
const height = document.getElementById('height');
const types = document.getElementById('types');
const hp = document.getElementById('hp');
const attack = document.getElementById('attack');
const defense = document.getElementById('defense');
const specialAttack = document.getElementById('special-attack');
const specialDefense = document.getElementById('special-defense');
const speed = document.getElementById('speed');
const sprite = document.getElementById('sprite');
searchButton.addEventListener('click', async () => {
const searchTerm = searchInput.value.toLowerCase();
clearPokemonInfo(); // Clear previous data before searching
const loadingMessage = document.createElement('p');
loadingMessage.textContent = 'Loading...';
pokemonInfo.appendChild(loadingMessage);
try {
const response = await fetch(`https://pokeapi.co/api/v2/pokemon/${searchTerm}`);
if (!response.ok) {
throw new Error(`Pokémon not found (HTTP status: ${response.status})`);
}
const pokemonData = await response.json();
validatePokemonData(pokemonData, searchTerm);
await displayPokemonInfo(pokemonData); //Await the display
} catch (error) {
const errorMessage = document.createElement('p');
errorMessage.textContent = `Error: ${error.message}`;
errorMessage.style.color = 'red';
pokemonInfo.appendChild(errorMessage);
} finally {
pokemonInfo.removeChild(loadingMessage); //Remove loading message
}
});
async function displayPokemonInfo(pokemonData) {
pokemonName.textContent = pokemonData.name.toUpperCase();
pokemonId.textContent = pokemonData.id;
weight.textContent = pokemonData.weight;
height.textContent = pokemonData.height;
hp.textContent = pokemonData.stats.find(stat => stat.stat.name === 'hp').base_stat;
attack.textContent = pokemonData.stats.find(stat => stat.stat.name === 'attack').base_stat;
defense.textContent = pokemonData.stats.find(stat => stat.stat.name === 'defense').base_stat;
specialAttack.textContent = pokemonData.stats.find(stat => stat.stat.name === 'special-attack').base_stat;
specialDefense.textContent = pokemonData.stats.find(stat => stat.stat.name === 'special-defense').base_stat;
speed.textContent = pokemonData.stats.find(stat => stat.stat.name === 'speed').base_stat;
sprite.src = pokemonData.sprites.front_default;
//Improved type display
const typesElement = document.createElement('p');
typesElement.innerHTML = 'Types: ';
pokemonData.types.forEach(type => {
const typeIcon = document.createElement('img');
typeIcon.src = `type-icons/${type.type.name}.png`; //Requires type-icons folder with images
typeIcon.alt = type.type.name;
typeIcon.width = '20';
typeIcon.height = '20';
typesElement.appendChild(typeIcon);
typesElement.appendChild(document.createTextNode(type.type.name.toUpperCase() + ' '));
});
pokemonInfo.appendChild(typesElement);
// Fetch and display abilities - more robust handling of errors and multiple abilities
const abilities = await Promise.all(pokemonData.abilities.map(async ability => {
const response = await fetch(ability.url);
if (!response.ok) {
console.error(`Error fetching ability: ${ability.url}`, response.status);
return null; //Handle failed ability fetch gracefully
}
const abilityData = await response.json();
return abilityData.name; // Return just the name of the ability
}));
const abilitiesList = abilities.filter(a => a !== null).join(', '); //Filter out null values before joining.
const abilitiesElement = document.createElement('p');
abilitiesElement.innerHTML = `Abilities: ${abilitiesList}`;
pokemonInfo.appendChild(abilitiesElement);
}
function validatePokemonData(pokemonData, searchTerm) {
// Add your validation logic here based on the test cases. For example:
if (searchTerm === 'pikachu') {
// ... (Your Pikachu validation code) ...
} else if (searchTerm === '94') {
// ... (Your Gengar validation code) ...
}
//Add other validations as needed.
}
function clearPokemonInfo() {
while (pokemonInfo.firstChild) { //Completely clear the pokemonInfo div.
pokemonInfo.removeChild(pokemonInfo.firstChild);
}
}
< /code>
Я попытался искать Пикачу на самом API, и он работает, так что на моем конце не так.>
Подробнее здесь: [url]https://stackoverflow.com/questions/79502377/my-pokeapi-is-getting-fetch-error-but-why[/url]
Ответить
1 сообщение
• Страница 1 из 1
Перейти
- Кемерово-IT
- ↳ Javascript
- ↳ C#
- ↳ JAVA
- ↳ Elasticsearch aggregation
- ↳ Python
- ↳ Php
- ↳ Android
- ↳ Html
- ↳ Jquery
- ↳ C++
- ↳ IOS
- ↳ CSS
- ↳ Excel
- ↳ Linux
- ↳ Apache
- ↳ MySql
- Детский мир
- Для души
- ↳ Музыкальные инструменты даром
- ↳ Печатная продукция даром
- Внешняя красота и здоровье
- ↳ Одежда и обувь для взрослых даром
- ↳ Товары для здоровья
- ↳ Физкультура и спорт
- Техника - даром!
- ↳ Автомобилистам
- ↳ Компьютерная техника
- ↳ Плиты: газовые и электрические
- ↳ Холодильники
- ↳ Стиральные машины
- ↳ Телевизоры
- ↳ Телефоны, смартфоны, плашеты
- ↳ Швейные машинки
- ↳ Прочая электроника и техника
- ↳ Фототехника
- Ремонт и интерьер
- ↳ Стройматериалы, инструмент
- ↳ Мебель и предметы интерьера даром
- ↳ Cантехника
- Другие темы
- ↳ Разное даром
- ↳ Давай меняться!
- ↳ Отдам\возьму за копеечку
- ↳ Работа и подработка в Кемерове
- ↳ Давай с тобой поговорим...
Мобильная версия