从php页面获取数据并在react js视图中显示

时间:2019-10-16 12:16:13

标签: php ajax reactjs api

我有一个react js Web应用程序。我想从服务器中获取数据,但出现如下错误:

  

未捕获(承诺)SyntaxError:意外令牌<位于JSON中的位置0

     

CORS策略已阻止从来源“ http://192.168.8.110/data.php”访问“ http://192.168.8.110:3000”处的XMLHttpRequest:请求的资源上没有“ Access-Control-Allow-Origin”标头。

我已经使用npm和create-react-app构建了我的react应用。

PHP文件路径为:

  

/usr/local/www/basic/reactproject/data.php

和我要获取数据的js文件是:

  

/usr/local/www/basic/reactproject/src/routes/dashboard.js

这是PHP代码:

<?php
echo'{"page":1,"per_page":6,"total":12,"total_pages":2,"data":[{"id":1,"email":"george.bluth@reqres.in","first_name":"George","last_name":"Bluth","avatar":"https://s3.amazonaws.com/uifaces/faces/twitter/calebogden/128.jpg"},{"id":2,"email":"janet.weaver@reqres.in","first_name":"Janet","last_name":"Weaver","avatar":"https://s3.amazonaws.com/uifaces/faces/twitter/josephstein/128.jpg"},{"id":3,"email":"emma.wong@reqres.in","first_name":"Emma","last_name":"Wong","avatar":"https://s3.amazonaws.com/uifaces/faces/twitter/olegpogodaev/128.jpg"},{"id":4,"email":"eve.holt@reqres.in","first_name":"Eve","last_name":"Holt","avatar":"https://s3.amazonaws.com/uifaces/faces/twitter/marcoramires/128.jpg"},{"id":5,"email":"charles.morris@reqres.in","first_name":"Charles","last_name":"Morris","avatar":"https://s3.amazonaws.com/uifaces/faces/twitter/stephenmoon/128.jpg"},{"id":6,"email":"tracey.ramos@reqres.in","first_name":"Tracey","last_name":"Ramos","avatar":"https://s3.amazonaws.com/uifaces/faces/twitter/bigmancho/128.jpg"}]}'
?>

这是dashboard.js:

import React from 'react';

class Dashboard extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      hits: []
    };
  }
  componentDidMount() {
    fetch("../data.php")
    .then(response => response.json())
    .then(data => 
      this.setState({ hits: data.data},
        this.props.removeLoading()
      )
    )
  }

  render() {
    const { hits } = this.state;  
    console.log(hits)
    return (
      <ul>
        {hits.map(hit =>
          <li key={hit.id}>
            <span>{hit.email}</span>
            <img src={hit.avatar} alt="images"/>
          </li>
        )}
      </ul>
    );
  }
}
export default Dashboard;

1 个答案:

答案 0 :(得分:0)

CORS用于访问不同域上的Web资源。为了将您的Web应用程序连接到服务器,您需要取消阻止“ ACCESS-CONTROL-ALLOW-ORIGIN”。您可以通过在Chrome浏览器中添加扩展程序来实现。链接如下。

https://chrome.google.com/webstore/detail/cors-unblock/lfhmikememgdcahcdlaciloancbhjino

OR

https://chrome.google.com/webstore/detail/allow-cors-access-control/lhobafahddgcelffkeicbaginigeejlf