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

时间:2019-02-19 09:21:11

标签: php

因此,我试图使一个端点使用来访问我的数据库,它在邮递员中工作得很好,但是在我的网站上调用GET请求时,出现了CORS错误:

  

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

我尝试使用谷歌搜索,但是找不到有用的东西。

我的服务器端代码位于2个文件中,这些文件包括在下面:

models / 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;
    }
}

log.php     

// 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")
      );
  }
}

1 个答案:

答案 0 :(得分:0)

原来是由于php不允许我使用类名“ Log”重命名了所有名为log的东西,现在它可以正常工作了。