Markdown

[php] Access-Control-Allow-Origin

KEY WORD : Cross-Origin Resource Sharing (CORS)
https://blog.m157q.tw/posts/2016/09/07/cross-origin-resource-sharing/


```
<DOCTYPE>
    <html>

    <head>
        <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
        <title>TEST CATCH API</title>
        <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
        <script>
            var Submit = function() {
                var URLs = "recive.php";

                $.ajax({
                    url: 'http://test123',
                    // data: $('#sentToBack').serialize(),
                    type: "GET",
                    dataType: 'text',

                    success: function(msg) {
                        // alert(msg);
                        console.log(msg)
                        var message = JSON.parse(msg)
                        document.write(message[0].id + '<br>');
                        document.write(message[0].updatedAt + '<br>');
                        document.write(message[0].publishedAt + '<br>');
                        document.write(message[0].userName + '<br>');
                        document.write(message[0].msg + '<br>');
                        //document.write(msg);
                    },

                    error: function(xhr, ajaxOptions, thrownError) {
                        alert(xhr.status);
                        alert(thrownError);
                    }
                });

            }
        </script>
    </head>

    <body>
        <form id="sentToBack">
            <input type="text" name="Text" />
            <input type="button" value="送出" onClick="Submit()" />
        </form>
    </body>

    </html>
```

How to solve the client side "Access-Control-Allow-Origin" request error with your own Symfony 3 API:

http://ourcodeworld.com/articles/read/291/how-to-solve-the-client-side-access-control-allow-origin-request-error-with-your-own-symfony-3-api


```
<?php

public function apiAction(){
    $response = new Response();
    $date = new \DateTime();

    $response->setContent(json_encode([
        'id' => uniqid(),
        'time' => $date->format("Y-m-d")
    ]));

    $response->headers->set('Content-Type', 'application/json');
    // Allow all websites
    $response->headers->set('Access-Control-Allow-Origin', '*');
    // Or a predefined website
    //$response->headers->set('Access-Control-Allow-Origin', 'https://jsfiddle.net/');
    // You can set the allowed methods too, if you want    //$response->headers->set('Access-Control-Allow-Methods', 'POST, GET, PUT, DELETE, PATCH, OPTIONS');  
    return $response;
}
```

https://stackoverflow.com/questions/40481059/access-control-allow-origin-in-symfony

不過在開了權限之後,還是會噴一樣的錯,
這時候可以去檢查 RESPONSE 的那隻 FUNCTION 是否是正確的,
因為像我為了測試註解掉某幾行,導致SERVER端噴錯,這時候就會沒辦法RESPONSE出來。
CLIENT 一樣會跑出 Access-Control-Allow-Origin NULL 的 error

留言