duanke3985
2019-02-19 09:21
浏览 782
已采纳

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

So I'm trying to make an endpoint to access my database with and it works just fine in postman, but when calling the GET request on my website i get a CORS error:

Query for foreign site blocked: The same origin policy does not allow remote resource reading http://IPGOESHERE/cordova/endpoint/log.php?id=-1. (Cause: The CORS query failed).)

I've tried googling but was unable to find anything useful.

My server-sided code is in 2 files which i have included below:

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条回答 默认 最新

相关推荐 更多相似问题