Проблема с использованием Fetch для получения значения JSON и вывода в виде текста в html - PullRequest
0 голосов
/ 30 апреля 2020

Я пытаюсь получить значение из API и вывести его в мой html код в виде текста. Ссылка API - «https://financialmodelingprep.com/api/v3/company/profile/AAPL» (данные в JSON). Код ниже - моя попытка получить цену. Моя конечная цель состоит в том, чтобы пользователь ввел тикер акций в поле ввода, а цена акции должна быть выведена в виде текста. Я успешно использовал функцию document.value для возврата значений при нажатии кнопки, но я не могу заставить его работать, используя API и выборку.

Большое спасибо!

    <!DOCTYPE html>
    <html>
    <head>
        <title>Pareto</title>

        <script>

        function xStockPrice(); {
            const fetch = require("node-fetch");

            const apiURL = "https://financialmodelingprep.com/api/v3/company/profile/AAPL"

            fetch(apiUrl)
                .then((res) =>res.json())
                .then(data => console.log(data.profile.price))

            document.tickerInputForm.output.value=data.profile.price
        }
        </script>

    </head>
    <body>
        <form name="tickerInputForm">
            <input type="text" name="xTicker"/>
            <input type="button" value="Get Quote" onclick="xStockPrice();"/>
            <input type="text" name="output"/>
        </form>
    </body>
    </html>

Ответы [ 2 ]

0 голосов
/ 01 мая 2020

Ошибка в вашем коде - точка с запятой в объявлении вашей функции function xStockPrice();

Должно быть так:

function xStockPrice(){
    const fetch = require("node-fetch");

    const apiURL = "https://financialmodelingprep.com/api/v3/company/profile/AAPL"

    fetch(apiURL)
        .then((res) => res.json())
        .then(data => {
            console.log(data.profile.price);
            document.tickerInputForm.output.value = data.profile.price;
        })
        .catch(error => console.log(error));
}

Использование JavaScript fetch ваш код работает нормально.

<!DOCTYPE html>
<html>
  <head>
    <title>Pareto</title>

    <script>
      function xStockPrice() {
        // const fetch = require("node-fetch");

        const apiURL =
          "https://financialmodelingprep.com/api/v3/company/profile/AAPL";
   
        fetch(apiURL)
          .then(res => res.json())
          .then(data => {
            console.log(data.profile.price);
           
            document.tickerInputForm.output.value = data.profile.price;
          })
          .catch(error => console.log(error));
      }
    </script>
  </head>
  <body>
    <form name="tickerInputForm">
      <input type="text" name="xTicker" />
      <input type="button" value="Get Quote" onclick="xStockPrice();" />
      <input type="text" name="output" />
    </form>
  </body>
</html>
0 голосов
/ 30 апреля 2020

У вас просто несколько мелких ошибок в коде, это должно выглядеть так:

function xStockPrice(); {
    const fetch = require("node-fetch");

    const apiURL = "https://financialmodelingprep.com/api/v3/company/profile/AAPL"
    // Before you used apiUrl, JavaScript variables are case sensitive
    // so apiURL is not the same as apiUrl and vice versa
    fetch(apiURL)
        .then((res) => res.json())
        .then(data => {
            console.log(data.profile.price);
            // Before this line lived outside of your then handler
            // Which causes two issues:
            // 1: data will be undefined, it only exists in the scope of this anonymous function
            // 2: The code will execute before your request is finished, you use then to wait for the response, so even if you had created the variable data before, it would be undefined when this line was executed, you use then to fill in the value and then you can use it to set the value of your input element
            document.tickerInputForm.output.value = data.profile.price;
        })
        .catch(error => console.log(error));
}
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...