这个问题在这里已有答案:
对于一个项目,我从我的localhost上的数据库中获取数据。我通过PHP文件获取数据并使用Javascript获取它并在HTML中实现数据。
但是当我获取时,我收到以下错误:
从' http:// localhost ' 访问' https://localhost/RetroTiles/assets/php/users.php ' 的访问权限已被CORS策略阻止:没有'Access-Control-Allow-Origin'标头存在在请求的资源上。如果不透明响应满足您的需求,请将请求的模式设置为“no-cors”以获取禁用CORS的资源。
我知道有一个解决方法然而我想知道为什么我现在得到这个错误,因为我的其他文件的其他fetch尝试没有错误。
let url = "https://localhost/RetroTiles/assets/php/users.php";
fetch(url).then(data => data.json()).then( data => implementUsers(data));
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;
我已经使用此方法获取数据以放入表格,并且没有错误。
发布于 2019-06-05 16:00:37
您还应该添加此标头:
header("Access-Control-Allow-Origin: *");
https://stackoverflow.com/questions/-100006933
复制相似问题