reactjs - 如何使用 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 没有返回任何内容......
解决方案
修复最终出现在我的 fetch 方法中,现在更新为:
fetch(URL)
.then(function(response) {
return response.json();
})
.then(function(myJson) {
console.log(JSON.stringify(myJson));
});
推荐阅读
- javascript - 如何让 puppeteer 点击链接?
- mysql - sqlalchemy.exc.OperationalError: (pymysql.err.OperationalError) (2003, "Can't connect to MySQL server
- javascript - RN webrtc - 远程流并不总是根据Wifi或移动网络显示
- vb6 - Visual Basic 6 vbp 文件随机损坏
- google-apps-script - 使用谷歌脚本在登录时抓取数据
- spring-boot - Spring Cloud Stream 与 RabbitMQ binder 和 Transactional consumer/producer 与 DB 操作
- reactjs - 我应该如何在我的反应新闻应用程序上实施身份验证?
- javascript - firebase httpsCallable 没有被调用/没有响应
- sql - 在存储过程中没有得到预期的结果
- javascript - 如何检测 div 文本的变化?