【发布时间】:2018-03-18 15:27:01
【问题描述】:
我正在尝试从 API 获取记录,但是当我使用以下代码时它返回不成功的响应。但同时,它在邮递员中使用状态码 200 给了我正确的响应。这是我的代码。请帮忙:
import React, {Component} from "react";
const urlEndPoint = myEndPoint => "https://api.github.com/users/adhishlal"
export default class Categories extends Component {
constructor(props) {
super(props)
this.state = {
requestFailed: false
}
}
componentDidMount() {
fetch(urlEndPoint(this.props.myEndPoint))
.then(response => {
if (!response.ok) {
throw Error(response.statusText)
}
return response
})
.then(d => response.json())
.then(response => {
this.setState({
responseData: d
})
}, () =>
{
this.setState({
requestFailed: true
})
})
}
render() {
//If request is failed
if(this.state.requestFailed)
{
return <div>Request Failed</div>
}
//Waiting for data to load from Zoho
if(!this.state.responseData)
{
return <div>Loading...</div>
}
//Finally populate the data when loaded
var indents = [];
for (var i = 0; i < 10; i++) {
indents.push(
<div className="col-sm-4 col-xs-12"><div className="cr-openings">
<p className="no-margin font-color-lightGrey no-of-openings">{i+1}</p><p className="catg-openings font-color-white">{this.state.responseData.name}</p>
<p className="font-color-lightGrey city-openings no-margin">Bangalore , Chennai , Delhi NCR , Hyderabad , Mumbai</p>
</div>
</div>
);
}
return (
<section className="dotted">
<div className="dotted-bg-dark">
<div className="container padding-80-0">
<div className="row m-b-30">
{indents}
</div>
</div>
</div>
</section>
);
}
}
你能建议我在哪里犯错吗?您可以在 restclient 或 postman 中运行 API 以查看响应。
【问题讨论】:
-
听起来像是 CORS 问题。您的端点网址是否启用了 CORS?
-
@Souradeep Nanda 也检查了 CORS。它没有帮助。
标签: json reactjs api fetch fetch-api