我正在尝试记录从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 返回任何内容......
修复程序最终在我的获取方法中,现在更新为:
fetch(URL)
.then(function(response) {
return response.json();
})
.then(function(myJson) {
console.log(JSON.stringify(myJson));
});