我正在从OMDB API获取一个API,并得到这个输出(TypeError: Failed to fetch)。
我用Postman测试了API,得到了肯定的响应。我的应用程序只有一个输入框和一个搜索按钮!它应该在用户输入标题时显示电影。
class App extends React.Component {
//state that stores the movies fetched from imdb database
state = {
movies: []
}
//sendRequest function that uses unirest to get our movie information.
sendRequest = (Title) => {
const req = unirest("GET", "http://www.omdbapi.com/?i=tt3896198&apikey=275a2eec");
req.query({
"page": "1",
"r": "json",
"s": Title
});
req.headers({
"x-rapidapi-host": "The OMDb API",
"x-rapidapi-key": "275a2eec"
});
req.end((res) => {
if (res.error) throw new Error(res.error);
//We’re pulling our movies out of the response data, and storing them in our app state.
const movies = res.body.Search;
this.setState({
movies
});
console.log(res.body);
});
}
}发布于 2021-09-27 08:00:01
通常,当响应头的Access-Control-Allow-Origin和请求的来源不匹配时,我们会得到这个错误。
有关详细的解释,请查看此article。
如果您在本地主机上测试此应用程序,可以尝试将http更改为https。这是一种简单的解决方案,有时适用于这种类型的错误。
https://stackoverflow.com/questions/60282960
复制相似问题