【问题标题】:How to solve the Cors issue with the sample google my business api code如何使用示例 google my business api 代码解决 Cors 问题
【发布时间】:2020-08-19 09:34:53
【问题描述】:

我正在尝试列出所有允许我的平台管理其帐户的帐户。我正在使用客户端库中给出的相同代码来获取请求,但是当我单击获取帐户按钮时,我遇到了 cors 问题,任何人都可以建议我如何解决这个问题,这里是 index.html 的代码

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
    <title>Google My Business Minimum Viable Platform Demo</title>
    <link rel="stylesheet" href="gmbdemo.css" />
  </head>

  <body>
    <h1 id="oauth-banner">
      Please confirm your API credentials and successful OAuth authorization.
    </h1>

    <div
      style="display: flex; flex-direction: column; width: 50%; float: left;"
    >
      <div>
        <div class="section">OAuth Consent</div>
        <div class="verbage">
          Trigger one-time OAuth consent, obtain a Refresh token and use it to
          fetch an Access token used in calls to API methods as described by
          <a href="https://developers.google.com/identity/protocols/OAuth2"
            >Using OAuth 2.0 to Access Google APIs</a
          >
        </div>
        <div>
          <button id="authorize-button" onclick="handleAuthClick()">
            OAuth2 Authorize
          </button>
          <button id="signout-button" onclick="handleSignoutClick()">
            OAuth2 Sign Out
          </button>
        </div>
      </div>
      <div>
        <div class="section">Accounts</div>
        <div>
          <button id="accounts-button" onclick="handleAccountsClick()">
            Get Accounts
          </button>
        </div>
      </div>

      <div>
        <div class="section">Account Admins and Locations</div>
        <div class="verbage">
          These commands operate on an individual account name. The name value
          can be found in the <i>locations.name</i> field of a
          <b>Get Accounts</b> response.
        </div>
        <div>
          <form id="accounts-form">
            <label for="accountName"> name </label>
            <input
              id="accountName"
              name="accountName"
              value="accounts/116981476297479439039"
            />
          </form>
        </div>
        <div>
          <button id="admins-button" onclick="handleAdminsClick()">
            Get Account Admins
          </button>
          <button id="locations-button" onclick="handleLocationsClick()">
            Get Locations
          </button>
        </div>
      </div>
    </div>

    <div
      style="display: flex; flex-direction: column; width: 50%; float: right;"
    >
      <div class="section">API Request</div>
      <pre id="request-area"></pre>
      <div class="section">API Response</div>
      <pre id="response-area"></pre>
    </div>

    <script src="gmbdemo.js"></script>
    <script
      src="https://apis.google.com/js/api.js"
      onload="this.onload=function(){};handleClientLoad()"
    ></script>

    <script>
      var apiKey = "";
      var clientId = "";

      var gmb_api_version = "https://mybusiness.googleapis.com/v4";
      var scopes = "https://www.googleapis.com/auth/business.manage";
    </script>
  </body>
</html>

我得到了 cors 的错误,就像我在 localhost 5000 上运行的那样,这是我得到的错误

从源“http://localhost:5000”访问“https://mybusiness.googleapis.com/v4/accounts”的 XMLHttpRequest 已被 CORS 策略阻止:对预检请求的响应未通过访问控制检查:请求的资源上不存在“Access-Control-Allow-Origin”标头。 gmbdemo.js:130 GET https://mybusiness.googleapis.com/v4/accounts net::ERR_FAILED

这里是这个 gmbdemo.js 的 js 代码

/**  Load the API client and OAuth2 library */
function handleClientLoad() {
  gapi.load("client:auth2", initClient);
}

/** Initialize OAuth2 and register event handlers */
function initClient() {
  gapi.client
    .init({ apiKey: apiKey, clientId: clientId, scope: scopes })
    .then(function () {
      // Listen for sign-in state changes.
      gapi.auth2.getAuthInstance().isSignedIn.listen(updateSigninStatus);

      // Handle the initial sign-in state.
      updateSigninStatus(gapi.auth2.getAuthInstance().isSignedIn.get());
    });
}

/**
 * callback handler for OAuth2 after sign-in status has been received
 * @param {boolean} isSignedIn
 */
function updateSigninStatus(isSignedIn) {
  var e = document.getElementsByClassName("section");
  var bg = "#0367C4";

  if (isSignedIn == false) {
    bg = "red";
    document.getElementById("oauth-banner").style.visibility = "visible";
  } else {
    document.getElementById("oauth-banner").style.visibility = "hidden";
  }

  for (var i = 0; i < e.length; i++) {
    e[i].style.backgroundColor = bg;
  }
}

/**
 * Display request details
 * @param {string} type
 * @param {string} url
 * @param {string} request_body
 */
function htmlifyRequest(type, url, request_body) {
  document.getElementById("request-area").style.display = "inherit";
  document.getElementById("request-area").innerHTML =
    type +
    "\n" +
    url +
    "\nRequest Body:\n" +
    JSON.stringify(request_body, undefined, 2);
}

/**
 * Display detailed response outcome
 * @param {?XMLHttpRequest} xhr
 */
function htmlifyResponse(xhr) {
  document.getElementById("response-area").style.background = "";
  document.getElementById("response-area").style.display = "inherit";
  document.getElementById("response-area").innerHTML =
    "HTTP Response Code: " +
    xhr.status +
    "\nResponse Body:\n" +
    JSON.stringify(xhr.response, undefined, 2);
}

/**
 * Display detailed error response
 * @param {?XMLHttpRequest} xhr
 */
function htmlifyError(xhr) {
  htmlifyResponse(xhr);
  document.getElementById("response-area").style.background = "#F7BD67";
}

/**
 * We receive an HTTP Response code from the server and an endpoint reply
 * to our request in the response in body.
 * @param {string} type
 * @param {string} url
 * @param {string} request_body
 * @return {?XMLHttpRequest}
 */
function XHRequest(type, url, request_body) {
  // update here so we visually get a sense of the response time
  document.getElementById("request-area").innerHTML = "";
  document.getElementById("response-area").innerHTML = "";

  return new Promise(function (resolve, reject) {
    var req = new XMLHttpRequest();
    var user = gapi.auth2.getAuthInstance().currentUser.get();
    var oauthToken = user.getAuthResponse().access_token;

    req.responseType = "json";
    req.open(type, url);

    // Authorize this request to the API by adding the bearer token
    // to the HTTP Request Headers in the authorization field
    req.setRequestHeader("Authorization", "Bearer " + oauthToken);

    // Enable verbose debug
    req.setRequestHeader("X-GOOG-API-FORMAT-VERSION", "2 ");

    req.onload = function () {
      if (req.status == 200) {
        resolve(req);
      } else {
        // bad api request: policy violation, incorrect parameters, ...
        reject(req);
      }
    };

    req.onerror = function () {
      reject(
        Error(
          "Network Error: DNS, TLS or CORS preflight may have failed.<br>" +
            "Confirm that the API project permissions, the request URL " +
            "format and HTTP headers are set appropriately.<br>" +
            "For more information on CORS preflight failures please see: " +
            "https://developer.mozilla.org/en-US/docs/Glossary/" +
            "Preflight_request"
        )
      );
    };
    htmlifyRequest(type, url, request_body);

    var encoded_request = JSON.stringify(request_body);
    req.send(encoded_request);
  });
}

/** OAuth2 Authorize button press handler */
function handleAuthClick() {
  gapi.auth2.getAuthInstance().signIn();
}

/** OAuth2 Sign Out button press handler */
function handleSignoutClick() {
  gapi.auth2.getAuthInstance().signOut();
}

/** Fetch a list of accounts available to the caller */
function handleAccountsClick() {
  var url = gmb_api_version + "/accounts";

  XHRequest("GET", url).then(htmlifyResponse).catch(htmlifyError);
}

/** Fetch a list of admins for the specified account */
function handleAdminsClick() {
  var formData = new FormData(document.getElementById("accounts-form"));
  var url = gmb_api_version + "/" + formData.get("accountName") + "/admins";

  XHRequest("GET", url).then(htmlifyResponse).catch(htmlifyError);
}

/** Fetch all locations within the specified account */
function handleLocationsClick() {
  var formData = new FormData(document.getElementById("accounts-form"));
  var url = gmb_api_version + "/" + formData.get("accountName") + "/locations";

  XHRequest("GET", url).then(htmlifyResponse).catch(htmlifyError);
}

【问题讨论】:

    标签: javascript oauth-2.0 google-authentication google-my-business-api


    【解决方案1】:

    不知道你是否已经找到解决方案。

    只需在 JS 中删除这部分即可:

    req.setRequestHeader("X-GOOG-API-FORMAT-VERSION", "2 ");
    

    去掉那部分后,终于在这里解决了。

    【讨论】:

      猜你喜欢
      • 2015-10-02
      • 1970-01-01
      • 2017-06-10
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多