发出使用React中的承载代码从API获取数据的问题

时间:2018-05-10 10:15:22

标签: reactjs authorization

我尝试使用react进行API调用。我的代码看起来类似于下面的代码。当我尝试它时,我收到了日志记录错误(找不到404页)。

componentDidMount() {
        this.setState({loading: true})
        fetch('https://jsonplaceholder.typicode.com/users', {

          headers: new Headers({
             Authorization: "Bearer XXXXXXXXXXXXXXXXXXXXX",
            "Content-Type": "application/json"
          }),
          method: "GET",
          mode: 'no-cors'
        })

请帮我解决这个问题。

1 个答案:

答案 0 :(得分:0)

您必须删除content-type属性。请求的主体是空的,这就是它失败的原因。

W3C - Content-Type Header Field

  

Content-Type字段的目的是描述数据   完全包含在身体中,接收用户代理可以   选择适当的代理或机制来向其提供数据   用户,或以适当的方式处理数据。

<强>更新 如果您使用Chrome进行测试,请阅读此主题No 'Access-Control-Allow-Origin' header is present on the requested resource error

class MyApp extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
    	res : {},
    };
  }
  
  componentDidMount() {
        fetch('https://jsonplaceholder.typicode.com/users', {
             headers: new Headers({
             Authorization: "Bearer XXXXXXXXXXXXXXXXXXXXX",
          }),
          method: "GET"
        })
        .then(res => res.json())
        .then(json => this.setState({ res: json}));
 };
 
  render() {
    return (<div> { JSON.stringify(this.state) } </div>);
  };
}

ReactDOM.render(<MyApp />, document.body);
<div id="app"></div>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"></script>