Все еще борется с асинхронностью ... но как получается, что команда fetch при размещении внутри функции выдает "TypeError: Failed to fetch".
Выборка отлично работает вне функции при вызове при загрузке.
index.html
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>paulywill's Books API Example</title>
<link href="style.css" rel="stylesheet">
</head>
<body>
<h1>Books!</h1>
<div id="root"></div>
<form>
Search for books: <input id="title" type="text">
<button class="search-book">Submit</button>
</form>
<div id="content"></div>
<script src="test.js"></script>
</body>
</html>
test.js
document.querySelector('.search-book').addEventListener('click', getBook);
const apiKey = '[myapi]'
function convertHTML(str) {
newStr = str.replace(/ /g, "+");
return newStr
}
function getBook() {
let titleHolder = document.getElementById("title").value;
console.log("titleHolder: " + titleHolder);
let title = convertHTML(titleHolder)
console.log("the title: " + title);
url = `https://www.googleapis.com/books/v1/volumes?q=${title}&projection=full&key=${apiKey}`
console.log("url: " + url);
fetch(url)
.then(response => response.json())
.then(data => {
console.log(data.items); // Prints result from `response.json()` in getRequest
})
.catch(error => console.error(error))
}
