如何使用React Fetch修复来自iTunes API的零返回数据

时间:2019-06-21 05:23:49

标签: reactjs itunes-api

我试图记录从iTunes搜索api返回的数据,但继续获得返回长度0(第31行)。当console.logging URL时,输入值和url concat字符串按预期工作(第32行)。

api网址的cors-anywhere部分用于推迟与cors相关的任何错误。

import React, { Component } from "react";

class Search extends Component {
  fetchData() {
    //set search value to a var
    var searchParamater = document.getElementById("searchValue").value;
    console.log("searchParameter is: " + searchParamater);
    var inputValue;
    // check if searchValue has a space in it
    try {
      if (searchParamater === " ") {
        console.log("please type something into the search bar");
      } else if (searchParamater != null && searchParamater.indexOf(" ") > -1) {
        // Search value includes white space
        // find white space / /g and replace with '+'
        inputValue = searchParamater.replace(/ /g, "+");
      } else {
        inputValue = searchParamater;
      }
    } catch (err) {
      console.log(err);
    }

    console.log("inputValue is: " + inputValue);
    let URL = `https://cors-anywhere.herokuapp.com/https://itunes.apple.com/search?term=${inputValue}`;
    console.log(URL);

    fetch(URL) // itunes api link goes here
      .then(response => response.json)
      .then(parsedJSON => console.log(parsedJSON.length))
      .then(parsedJSON => console.log(parsedJSON.result))
      .catch(error => console.log("parsing failed", error));
  }
  render() {
    return (
      <Jumbotron fluid>
        <Container>
          <div />
          <Form>
            <Form.Group controlId="formBasicEmail">
              <Form.Label>
                <h2>Search On iTunes:</h2>
              </Form.Label>
              <Form.Control
                type="text"
                placeholder="Enter search"
                id="searchValue"
              />
              <Form.Text className="text-muted">
                We'll never share your searches with anyone else
              </Form.Text>
            </Form.Group>
            <Button onClick={this.fetchData}>Submit</Button>
          </Form>
          <div />
        </Container>
      </Jumbotron>
    );
  }
}

export default Search;

我希望在控制台中得到一个记录的返回JSON对象,但是json.count对象的值为0表示我没有从API返回任何信息...

1 个答案:

答案 0 :(得分:0)

此修复程序最终已在我的提取方法中更新为:

fetch(URL)
  .then(function(response) {
    return response.json();
  })
  .then(function(myJson) {
    console.log(JSON.stringify(myJson));
  });