[英]How to solve the Cors issue with the sample google my business api code
I am trying to list down all the accounts who have given my platform the access to manage their accounts.我正在尝试列出所有允许我的平台管理其帐户的帐户。 and i am using the same code which is given in the client libraries for getting the request but when i clicking on the get Accounts button i am facing cors issue can anyone suggest me how can i solve this issue here is the code of index.html
我正在使用客户端库中提供的相同代码来获取请求但是当我单击“获取帐户”按钮时我面临 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>
and i am getting the error of the cors like this way i am running on localhost 5000 and here is the error i am getting我得到了 cors 的错误,就像这样我在 localhost 5000 上运行,这是我得到的错误
Access to XMLHttpRequest at 'https://mybusiness.googleapis.com/v4/accounts' from origin 'http://localhost:5000' has been blocked by CORS policy: Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource. CORS 策略阻止了从来源“http://localhost:5000”访问“https://mybusiness.googleapis.com/v4/accounts”上的 XMLHttpRequest:对预检请求的响应未通过访问控制检查:否请求的资源上存在“Access-Control-Allow-Origin”header。 gmbdemo.js:130 GET https://mybusiness.googleapis.com/v4/accounts .net::ERR_FAILED
gmbdemo.js:130 GET https://mybusiness.googleapis.com/v4/accounts .net::ERR_FAILED
and here is the js code for this gmbdemo.js这是这个 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);
}
Don't know whether you already found a solution.不知道您是否已经找到解决方案。
Just remove this part in the JS:只需删除 JS 中的这部分:
req.setRequestHeader("X-GOOG-API-FORMAT-VERSION", "2 ");
After removing that part, it finally worked out here.删除那部分后,它终于在这里解决了。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.