PHP cURL 为特定端点添加了“Access-Control-Allow-Origin: *”标头


PHP cURL add "Access-Control-Allow-Origin: *" header for specific endpoint

我的php服务器(5.2)端点GET http://mydomain/get-code.php上有这样的代码:

<?php
    header("Access-Control-Allow-Origin: *");
    $data = 'id=' . '123456' . '&' .
            'text=' . 'some text' . '&' .
            'code=' . urlencode($_GET['code']);
    $ch = curl_init('https://someapi.com/login/oauth');
    curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    $response = curl_exec($ch);
    preg_match('/hash=([0-9a-f]+)/', $response, $out);
    echo $out[1];
    curl_close($ch);
?>

我正在从另一个域请求获取 http://mydomain/get-code.php。

我在浏览器控制台中收到 CORS 错误:

XMLHttpRequest cannot load http://mydomain/get-code.php No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://localhost:9292' is therefore not allowed access.

有什么想法吗?

Access-Control-Allow-Origin 适用于接收请求的服务器,而不是发送请求的客户端。