【发布时间】:2020-02-13 05:21:14
【问题描述】:
我有一个 react js web 应用程序。我想从服务器获取数据,但出现如下错误:
Uncaught (in promise) SyntaxError: Unexpected token
从源“http://192.168.8.110:3000”访问“http://192.168.8.110/data.php”处的 XMLHttpRequest 已被 CORS 策略阻止:请求的资源上不存在“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;
【问题讨论】:
-
我猜你用 PHP 返回的 JSON 的内容类型不正确。尝试设置一个标头,并返回一个 JSON 作为字符串尝试
json_encode一个数组,这样你就可以确保你的 JSON 是有效的。 -
@techouse 感谢您的评论。我已经通过相同的结果尝试了一个 API,它工作正常。但它不是这样工作的!
-
然后尝试将
header('Content-Type: application/json; charset=utf-8');添加到 PHP 并正确返回 JSON。 -
@techouse 仍然无法正常工作。我试过的 API 是这样的:reqres.in/api/users?delay=3
-
你为什么不直接使用.json文件而不是通过php回显?