【问题标题】:Firebase Dynamic Link CORS - XMLHttpRequestFirebase 动态链接 CORS - XMLHttpRequest
【发布时间】:2018-11-26 15:32:30
【问题描述】:

我想使用 Firebase 动态链接缩短器来缩短我的网址。我关注了其余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 错误:

跨域请求被阻止:同源策略不允许读取 远程资源在 https://firebasedynamiclinks.googleapis.com/v1/shortLinks?key=MY_API_KEY。 (原因:CORS 标头“Access-Control-Allow-Origin”缺失)。

我似乎找不到可以启用跨域请求的设置。谁能告诉我如何在浏览器中使用 Firebase 动态链接?

【问题讨论】:

    标签: firebase xmlhttprequest cross-domain firebase-dynamic-links cross-domain-policy


    【解决方案1】:

    我通过创建一个 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();
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2022-12-03
      • 2018-12-25
      • 2021-01-18
      • 2020-03-18
      • 2021-09-26
      • 2021-06-24
      相关资源
      最近更新 更多