php handle CORS http api request in Unity WebGL project

Unity 可以將專案 deploy 到 web 環境中執行,但此時送 http api request 的時候,就會有 CORS 需要處理。

現在很多前端的程式都是直接就送 api request, 不會先送個 HTTP OPTIONS給 api server 詢問可使用的方法(reference)後,才送出真正的 api request (唔,該說是個有禮貌的孩子?)

總之在 server 上就需要處理這個 OPTIONS request。因為我這邊的例子(in phalcon framework)中,真正的 api request 把參數用 json 格式傳送,所以 api request 的 header 會預期有 content-type: application/json,因此在處理 OPTIONS request 時,要加上允許 Content-Type。

public function testAction()
{
    $this->view->disable();
    if ($this->request->getMethod() == "OPTIONS")
    {
        header('Access-Control-Allow-Methods: GET, POST, OPTIONS');
        header('Access-Control-Allow-Origin: *');
        header('Access-Control-Allow-Headers: X-Requested-With, Content-Type');
        exit;
    }
    else
    {
        $data = $this->request->getJsonRawBody(true);

        echo $data["b64"];
        return;
    }
}