如何修复 PHP 中的 CORS 错误?(CORS没有成功)

免责声明

所以我试图创建一个端点来访问我的数据库,它在邮递员中工作得很好,但是GET在我的网站上调用请求时,我收到一个 CORS 错误:

查询国外站点被阻止:同源策略不允许远程资源读取http://IPGOESHERE/cordova/endpoint/log.php?id=-1(原因:CORS 查询失败)。

我试过谷歌搜索,但找不到任何有用的东西。

我的服务器端代码包含在下面的 2 个文件中:

模型/Log.php:

class Log {

  // database connection and table name
  private $conn;
  private $table_name = "logging";

  // object properties
  public $ID;
  public $UserID;
  public $Handling;
  public $Date;

  // constructor with $db as database connection
  public function __construct($db) {
      $this->conn = $db;
  }

  // read products
  function read($id) 
  {
        $query = "SELECT * FROM " . $this->table_name;

        if ($id != '-1') {
            // select query
            $query .= " WHERE logging.ID = ".$id;
        }
        // prepare query statement
        $stmt = $this->conn->prepare($query);

        // execute query
        $stmt->execute();

        return $stmt;
    }
}

日志文件

// required headers
header("Access-Control-Allow-Origin: *");
header("Access-Control-Allow-Credentials: true");
header("Access-Control-Max-Age: 1000");
header("Access-Control-Allow-Headers: X-Requested-With, Content-Type, Origin, Cache-Control, Pragma, Authorization, Accept, Accept-Encoding");
header("Access-Control-Allow-Methods: PUT, POST, GET, OPTIONS, DELETE");
header("Content-Type: application/json; charset=UTF-8");

// database connection will be here
include_once '../database.inc';
include_once '../models/Log.php';

if ($_SERVER['REQUEST_METHOD'] === 'GET') {
  $id = $_GET['id'];

  $database = new Database();
  $db = $database->getConnection();

  $Log = new Log($db);
  // query products
  $stmt = $Log->read($id);
  $num = $stmt->rowCount();

  // check if more than 0 record found
  if ($num > 0) {
      $products_arr = array();
      $products_arr["records"] = array();

      while ($row = $stmt->fetch(PDO::FETCH_ASSOC)){
          extract($row);

          $product_item = array(
              "ID" => $ID,
              "UserID" => $UserID,
              "Handling" => $Handling,
              "Date" => $Date,
          );

          array_push($products_arr["records"], $product_item);
      }

      // set response code - 200 OK
      http_response_code(200);

      // show products data in json format
      echo json_encode($products_arr);
  } else {
      // set response code - 404 Not found
      http_response_code(404);

      // tell the user no products found
      echo json_encode(
          array("message" => "No log found")
      );
  }
}
免责声明

原来这是由于 php 不允许我使用类名“Log”重命名了所有名为 log 的内容,现在它可以完美运行。

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章