Firebase 动态 Link CORS - XMLHttpRequest

Firebase Dynamic Link CORS - XMLHttpRequest

我想使用 Firebase Dynamic Link 缩短我的 URL。我跟着休息 API reference 代码似乎检查出来了:

const url ="https://firebasedynamiclinks.googleapis.com/v1/shortLinks?key=MY_API_KEY";

this.request = new XMLHttpRequest();
this.request.open("GET", url, true);
this.request.setRequestHeader("Content-Type", "application/json");
this.request.setRequestHeader("Access-Control-Allow-Origin", "*");

const parameters = {
    "longDynamicLink": encodeURIComponent(window.location)
  };

this.request.onreadystatechange = this.updateLink;
this.request.send(parameters);

但是当我执行这段代码时,出现 CORS 错误:

Cross-Origin Request Blocked: The Same Origin Policy disallows reading the remote resource at https://firebasedynamiclinks.googleapis.com/v1/shortLinks?key=MY_API_KEY. (Reason: CORS header ‘Access-Control-Allow-Origin’ missing).

我似乎找不到可以启用跨源请求的设置。谁能告诉我如何从浏览器使用 Firebase Dynamic Links?

我通过创建一个 PHP 脚本解决了这个问题,我可以使用该脚本将 Firebase Rest 调用从客户端委托给服务器端。这也确保我的用户永远不会看到我的 Firebase API 密钥。

<?php
$LongDynamicLink = "MYHOST?" . urlencode($_GET["url"]);
$url = "https://firebasedynamiclinks.googleapis.com/v1/shortLinks?key=MY_API_KEY";
$data = '{
    "dynamicLinkInfo": {
      "dynamicLinkDomain": "MY_LINK_DOMAIN",
      "link": "' . $LongDynamicLink . '",
      "androidInfo": {
        "androidPackageName": "ANDROID_PACKAGE_NAME"
      },
      "iosInfo": {
        "iosBundleId": "IOS_BUNDLE_NAME"
      }
    }
  }';
echo httpPost($url, $data);
function httpPost($url, $data)
{
    $curl = curl_init($url);
    curl_setopt($curl, CURLOPT_POST, true);
    curl_setopt($curl, CURLOPT_HTTPHEADER, array('Content-Type: application/json'));
    curl_setopt($curl, CURLOPT_POSTFIELDS, $data);
    curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
    $response = curl_exec($curl);
    curl_close($curl);
    return $response;
}
?>

使用此代码,您可以这样调用 PHP Rest API:

let request = new XMLHttpRequest();
request.open("GET", "MY_DOMAIN/?url=URL_I_WANT_TO_SHORTEN", true);
request.onreadystatechange = console.log(request.response);
request.send();