谷歌云 PHP CORS 问题

时间:2021-06-17 10:14:55

标签: php google-cloud-functions cors

我已使用 PHP(测试版)语言将 PHP api 迁移到谷歌云函数。代码从外部应用程序请求数据,该数据以 XML 格式返回,然后 API 获取结果并将其输出为 JSON 以供 angular 应用程序读取

我的代码在使用 POSTMAN 时有效(所以我知道它返回正确的数据)但是当从我的 Angular 应用程序在本地或托管在 google firebase 上运行时,我得到以下 CORS 问题

Request URL: [[google firebase cloud function url]]
Request Method: OPTIONS
Status Code: 500
Referrer Policy: strict-origin-when-cross-origin
Provisional headers are shown
Accept: application/json, text/plain, */*
Content-Type: application/moca-xml
Referrer: http://localhost:4200/
Response-Encoder: application/xml
Response-Type: text
Request Payload:
[[Data sent to external app to request data ]]

使用的原始 PHP API 通过设置标头绕过 CORS:

//set header of return output
header('Access-Control-Allow-Origin: *'); 
header("Access-Control-Allow-Credentials: true");
header('Access-Control-Allow-Methods: POST');
header('Access-Control-Max-Age: 1000');
header('Access-Control-Allow-Headers: Origin, Content-Type, Response-Encoder, Response-Type');  
header('Content-Type: application/json');

在 google firebase 云函数中,无论使用上面还是下面建议的方法都没有效果,导致 CORS 错误

$headers = ['Access-Control-Allow-Origin' => '*'];
$headers = array_merge($headers, [
            'Access-Control-Allow-Methods' => 'POST, OPTIONS',
            'Access-Control-Allow-Credentials' => 'true',
            'Access-Control-Allow-Headers' => 'Origin, Content-Type, Response-Encoder, Response-Type',
            'Access-Control-Max-Age' => '1000',
            'Content-Type' => 'application/json'            
        ]);

.... code to get data ....

return new Response(200, $headers, $returndata);


1 个答案:

答案 0 :(得分:-1)

首先,调用 google cloud PHP 函数的 angular 应用程序不允许某些标题,最后我的标题只是

private headers = new HttpHeaders({'Content-Type':'application/json'});

然后在谷歌云 PHP 函数中,必须通过返回 200 或 204 以及在响应中设置标头来处理 OPTIONS 请求

 $headers = ['Access-Control-Allow-Origin' => '*'];
 if ($request->getMethod() === 'OPTIONS') {
     $headers = array_merge($headers, [
            'Access-Control-Allow-Methods' => 'GET',
            'Access-Control-Allow-Headers' => 'Content-Type',
            'Access-Control-Max-Age' => '3600'          
        ]);
    return new Response(200, $headers, '');
 } else {
     $headers = array_merge($headers, [
                'Access-Control-Allow-Methods' => 'POST',
                'Access-Control-Allow-Credentials' => 'true',
                'Access-Control-Allow-Headers' => 'Origin, Content-Type',
                'Access-Control-Max-Age' => '1000', 
                'Content-Type' => 'application/json'    
            ]);
 }