API Google Книг - TypeError: Не удалось получить - PullRequest
0 голосов
/ 04 марта 2019

Все еще борется с асинхронностью ... но как получается, что команда 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))
}            

enter image description here

1 Ответ

0 голосов
/ 04 марта 2019

Понял.Подсказка была одним из ответов здесь :

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 onsubmit="handleClick(); return false;">
        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


const apiKey = '[myapi]'


function handleClick() {
    document.querySelector('.search-book').addEventListener('click', getBook);
}


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('hello')
            console.log(data) // Prints result from `response.json()` in getRequest
        })
        .catch(error => {
            console.log(error);
        });
    }
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...