首页
学习
活动
专区
工具
TVP
发布
社区首页 >问答首页 >从php文件中获取json时出现CORS错误[重复]

从php文件中获取json时出现CORS错误[重复]
EN

Stack Overflow用户
提问于 2019-06-05 06:53:37
回答 1查看 0关注 0票数 0

这个问题在这里已有答案:

  • Access-Control-Allow-Origin标头如何工作? 13个答案

对于一个项目,我从我的localhost上的数据库中获取数据。我通过PHP文件获取数据并使用Javascript获取它并在HTML中实现数据。

但是当我获取时,我收到以下错误:

从' http:// localhost ' 访问' https://localhost/RetroTiles/assets/php/users.php ' 的访问权限已被CORS策略阻止:没有'Access-Control-Allow-Origin'标头存在在请求的资源上。如果不透明响应满足您的需求,请将请求的模式设置为“no-cors”以获取禁用CORS的资源。

我知道有一个解决方法然而我想知道为什么我现在得到这个错误,因为我的其他文件的其他fetch尝试没有错误。

JavaScript的

let url = "https://localhost/RetroTiles/assets/php/users.php";
fetch(url).then(data => data.json()).then( data => implementUsers(data));

PHP

include_once "connect.php";

$query = "SELECT id, name FROM users
          ORDER BY id ASC";

$users = [];

//store the users in the array
if ($result = mysqli_query($connection, $query)) {
    while ($row = mysqli_fetch_assoc($result)) {
        $users[] = $row;
    }
}

//close database connection.
mysqli_close($connection);

//Set the content type to Json.
header("Content-Type: application/json");
echo json_encode($users);
exit;

我已经使用此方法获取数据以放入表格,并且没有错误。

EN

回答 1

Stack Overflow用户

发布于 2019-06-05 16:00:37

您还应该添加此标头:

header("Access-Control-Allow-Origin: *");
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/-100006933

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档