如何使用示例google my business api代码解决Cors问题

如何解决如何使用示例google my business api代码解决Cors问题

我正在尝试列出所有授予我平台访问权限以管理其帐户的帐户。我正在使用客户端库中提供的相同代码来获取请求,但是当我单击“获取帐户”按钮时,我遇到了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,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,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,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);
}

解决方法

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

只需在JS中删除此部分:

def getddpgModelEvalResult(env,hyperparamDict,numTrajToSample = 10):
    tf.reset_default_graph()
    
    totalrewards = []
    
    agent_test = Agent(
        alpha = hyperparamDict['actorLR'],beta = hyperparamDict['criticLR'],input_dims = [env.observation_space.shape[0]],tau = hyperparamDict['tau'],env = env_norm(env) if hyperparamDict['normalizeEnv'] else env,n_actions = env.action_space.shape[0],units1 = hyperparamDict['actorHiddenLayersWidths'],units2 = hyperparamDict['criticHiddenLayersWidths'],actoractivationfunction = hyperparamDict['actorActivFunction'],actorHiddenLayersWeightInit = hyperparamDict['actorHiddenLayersWeightInit'],actorHiddenLayersBiasInit = hyperparamDict['actorHiddenLayersBiasInit'],actorOutputWeightInit = hyperparamDict['actorOutputWeightInit'],actorOutputBiasInit = hyperparamDict['actorOutputBiasInit'],criticHiddenLayersWidths = hyperparamDict['criticHiddenLayersWidths'],criticActivFunction = hyperparamDict['criticActivFunction'],criticHiddenLayersBiasInit = hyperparamDict['criticHiddenLayersBiasInit'],criticHiddenLayersWeightInit = hyperparamDict['criticHiddenLayersWeightInit'],criticOutputWeightInit = hyperparamDict['criticOutputWeightInit'],criticOutputBiasInit = hyperparamDict['criticOutputBiasInit'],max_size = hyperparamDict['bufferSize'],gamma = hyperparamDict['gamma'],batch_size = hyperparamDict['minibatchSize'],initnoisevar = hyperparamDict['noiseInitVariance'],noiseDecay = hyperparamDict['varianceDiscount'],noiseDacayStep = hyperparamDict['noiseDecayStartStep'],minVar = hyperparamDict['minVar'],path = hyperparamDict['modelSavePathPhil']
        )
    
    agent_test.load_models()
    collection_rewards = []
    collection_estimation = []

    for i in range(numTrajToSample):
        obs = env.reset()
        rewards = 0
        estimated_rewards = 0
        for j in range(hyperparamDict['maxTimeStep']):
            trajectoryreward = []
            trajectoryestimate = []
            done = False
            
            act = agent_test.choose_test_action(obs,env.action_space.low,env.action_space.high)
            new_state,reward,done,info = env.step(act)
            

            obs_array = np.reshape(obs,[1,env.observation_space.shape[0]])
            act_array = np.reshape(act,env.action_space.shape[0]])
            
            estimated_rewards = agent_test.critic.predict(obs_array,act_array)
            trajectoryreward.append(reward)
            trajectoryestimate.append(estimated_rewards)
            obs = new_state

            if done:
               
                break
        collection_rewards.append(trajectoryreward)
        collection_estimation.append(np.mean(trajectoryestimate))
            

    
    
    # calculate the actual Q from reward
    actualQ_mean = []
    for item in range(len(collection_rewards)):
        actualQ = []
        temp = collection_rewards[item]
        length = len(temp)
        for i in range(length):
            gamma_list = [hyperparamDict['gamma']**j for j in range(length)]
            reward_list = temp
            Q = sum([a*b for a,b in zip(gamma_list,reward_list)])
            actualQ.append(Q)
            temp.pop(0)
            length = len(temp)

        actualQ_mean.append(np.mean(actualQ))


    del agent_test

删除该部分后,终于在这里解决了问题。

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐


依赖报错 idea导入项目后依赖报错,解决方案:https://blog.csdn.net/weixin_42420249/article/details/81191861 依赖版本报错:更换其他版本 无法下载依赖可参考:https://blog.csdn.net/weixin_42628809/a
错误1:代码生成器依赖和mybatis依赖冲突 启动项目时报错如下 2021-12-03 13:33:33.927 ERROR 7228 [ main] o.s.b.d.LoggingFailureAnalysisReporter : *************************** APPL
错误1:gradle项目控制台输出为乱码 # 解决方案:https://blog.csdn.net/weixin_43501566/article/details/112482302 # 在gradle-wrapper.properties 添加以下内容 org.gradle.jvmargs=-Df
错误还原:在查询的过程中,传入的workType为0时,该条件不起作用 &lt;select id=&quot;xxx&quot;&gt; SELECT di.id, di.name, di.work_type, di.updated... &lt;where&gt; &lt;if test=&qu
报错如下,gcc版本太低 ^ server.c:5346:31: 错误:‘struct redisServer’没有名为‘server_cpulist’的成员 redisSetCpuAffinity(server.server_cpulist); ^ server.c: 在函数‘hasActiveC
解决方案1 1、改项目中.idea/workspace.xml配置文件,增加dynamic.classpath参数 2、搜索PropertiesComponent,添加如下 &lt;property name=&quot;dynamic.classpath&quot; value=&quot;tru
删除根组件app.vue中的默认代码后报错:Module Error (from ./node_modules/eslint-loader/index.js): 解决方案:关闭ESlint代码检测,在项目根目录创建vue.config.js,在文件中添加 module.exports = { lin
查看spark默认的python版本 [root@master day27]# pyspark /home/software/spark-2.3.4-bin-hadoop2.7/conf/spark-env.sh: line 2: /usr/local/hadoop/bin/hadoop: No s
使用本地python环境可以成功执行 import pandas as pd import matplotlib.pyplot as plt # 设置字体 plt.rcParams[&#39;font.sans-serif&#39;] = [&#39;SimHei&#39;] # 能正确显示负号 p
错误1:Request method ‘DELETE‘ not supported 错误还原:controller层有一个接口,访问该接口时报错:Request method ‘DELETE‘ not supported 错误原因:没有接收到前端传入的参数,修改为如下 参考 错误2:cannot r
错误1:启动docker镜像时报错:Error response from daemon: driver failed programming external connectivity on endpoint quirky_allen 解决方法:重启docker -&gt; systemctl r
错误1:private field ‘xxx‘ is never assigned 按Altʾnter快捷键,选择第2项 参考:https://blog.csdn.net/shi_hong_fei_hei/article/details/88814070 错误2:启动时报错,不能找到主启动类 #
报错如下,通过源不能下载,最后警告pip需升级版本 Requirement already satisfied: pip in c:\users\ychen\appdata\local\programs\python\python310\lib\site-packages (22.0.4) Coll
错误1:maven打包报错 错误还原:使用maven打包项目时报错如下 [ERROR] Failed to execute goal org.apache.maven.plugins:maven-resources-plugin:3.2.0:resources (default-resources)
错误1:服务调用时报错 服务消费者模块assess通过openFeign调用服务提供者模块hires 如下为服务提供者模块hires的控制层接口 @RestController @RequestMapping(&quot;/hires&quot;) public class FeignControl
错误1:运行项目后报如下错误 解决方案 报错2:Failed to execute goal org.apache.maven.plugins:maven-compiler-plugin:3.8.1:compile (default-compile) on project sb 解决方案:在pom.
参考 错误原因 过滤器或拦截器在生效时,redisTemplate还没有注入 解决方案:在注入容器时就生效 @Component //项目运行时就注入Spring容器 public class RedisBean { @Resource private RedisTemplate&lt;String
使用vite构建项目报错 C:\Users\ychen\work&gt;npm init @vitejs/app @vitejs/create-app is deprecated, use npm init vite instead C:\Users\ychen\AppData\Local\npm-