Skip to content

Commit

Permalink
Enable CORS (Cross-origin resource sharing)
Browse files Browse the repository at this point in the history
  • Loading branch information
MPrtenjak committed Sep 29, 2017
1 parent 131177b commit d349ca7
Showing 1 changed file with 18 additions and 1 deletion.
19 changes: 18 additions & 1 deletion source/Jacwright/RestServer/RestServer.php
Expand Up @@ -52,6 +52,8 @@ class RestServer {
public $jsonAssoc = false;
public $authHandler = null;

public $useCors = false;

protected $map = array();
protected $errorClasses = array();
protected $cached;
Expand Down Expand Up @@ -111,6 +113,11 @@ public function handle() {
$this->method = $this->getMethod();
$this->format = $this->getFormat();

if (($this->useCors) && ($this->method == 'OPTIONS')) {
$this->corsHeaders();
exit;
}

if ($this->method == 'PUT' || $this->method == 'POST' || $this->method == 'PATCH') {
$this->data = $this->getData();
}
Expand Down Expand Up @@ -459,6 +466,10 @@ public function sendData($data) {
header("Expires: 0");
header('Content-Type: ' . $this->format);

if ($this->useCors) {
$this->corsHeaders();
}

if ($this->format == RestFormat::XML) {
if (is_object($data) && method_exists($data, '__keepOut')) {
$data = clone $data;
Expand Down Expand Up @@ -535,7 +546,13 @@ private function xml_encode($mixed, $domElement = null, $DOMDocument = null) {
}
}


private function corsHeaders() {
header('Access-Control-Allow-Origin: *');
header('Access-Control-Allow-Methods: GET,POST,PUT,DELETE,OPTIONS');
header('Access-Control-Allow-Credential: true');
header('Access-Control-Allow-Headers: X-Requested-With, content-type, access-control-allow-origin, access-control-allow-methods, access-control-allow-headers, Authorization');
}

private $codes = array(
'100' => 'Continue',
'200' => 'OK',
Expand Down

0 comments on commit d349ca7

Please sign in to comment.