首页 > 解决方案 > 如何使用 React fetch 修复来自 iTunes api 的零返回数据

问题描述

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

api url 的 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 没有返回任何内容......

标签: reactjsitunes-api

解决方案


修复最终出现在我的 fetch 方法中,现在更新为:

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

推荐阅读