如何解决如何使用示例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 举报,一经查实,本站将立刻删除。