#google-sheets #electron #google-api-js-client #google-reporting-api
#google-sheets #electron #google-api-js-client #google-reporting-api
Вопрос:
Я использую конечную точку GAPI v4 для доступа к Google Sheets, я использовал пример из Google quickstart и получаю ошибку 404 Запрошенный объект не найден. Почему это должно происходить, этого не должно происходить, поскольку я использовал их пример, мой код:
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Application Conversion Viewer</title>
<!-- https://electronjs.org/docs/tutorial/security#csp-meta-tag -->
<!-- <meta http-equiv="Content-Security-Policy" content="script-src 'self' 'unsafe-inline';" /> -->
<meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.5.2/css/bootstrap.min.css" integrity="sha384-JcKb8q3iqJ61gNV9KGb8thSsNjpSL0n8PARn9HuZOnIxN0hoP VmmDGMN5t9UJ0Z" crossorigin="anonymous">
</head>
<body>
<div id="app">
<!--Add buttons to initiate auth sequence and sign out-->
<button id="authorize_button" style="display: none;">Authorize</button>
<button id="signout_button" style="display: none;">Sign Out</button>
<pre id="content" style="white-space: pre-wrap;"></pre>
</div>
<script src="https://cdn.jsdelivr.net/npm/vue/dist/vue.js"></script>
<script src="https://cdn.jsdelivr.net/npm/vue-resource@1.5.1"></script>
<script src="https://apis.google.com/js/api.js"></script>
<script>
new Vue({
el: '#app',
mounted () {
var authorizeButton = document.getElementById('authorize_button');
var signoutButton = document.getElementById('signout_button');
/**
* On load, called to load the auth2 library and API client library.
*/
function handleClientLoad() {
gapi.load('client:auth2', initClient);
}
/**
* Initializes the API client library and sets up sign-in state
* listeners.
*/
function initClient() {
gapi.client.init({
apiKey: 'MY-KEY',
clientId: 'MY-CLIENT-ID',
discoveryDocs: 'https://sheets.googleapis.com/$discovery/rest?version=v4',
scope: 'https://www.googleapis.com/auth/spreadsheets.readonly'
}).then(function () {
console.log('SUCCESS')
// Listen for sign-in state changes.
gapi.auth2.getAuthInstance().isSignedIn.listen(updateSigninStatus);
// Handle the initial sign-in state.
updateSigninStatus(gapi.auth2.getAuthInstance().isSignedIn.get());
authorizeButton.onclick = handleAuthClick;
signoutButton.onclick = handleSignoutClick;
}, function(error) {
console.log(error)
appendPre(JSON.stringify(error, null, 2));
});
}
/**
* Called when the signed in status changes, to update the UI
* appropriately. After a sign-in, the API is called.
*/
function updateSigninStatus(isSignedIn) {
if (isSignedIn) {
authorizeButton.style.display = 'none';
signoutButton.style.display = 'block';
listMajors();
} else {
authorizeButton.style.display = 'block';
signoutButton.style.display = 'none';
}
}
/**
* Sign in the user upon button click.
*/
function handleAuthClick(event) {
gapi.auth2.getAuthInstance().signIn();
}
/**
* Sign out the user upon button click.
*/
function handleSignoutClick(event) {
gapi.auth2.getAuthInstance().signOut();
}
/**
* Append a pre element to the body containing the given message
* as its text node. Used to display the results of the API call.
*
* @param {string} message Text to be placed in pre element.
*/
function appendPre(message) {
var pre = document.getElementById('content');
var textContent = document.createTextNode(message 'n');
pre.appendChild(textContent);
}
/**
* Print the names and majors of students in a sample spreadsheet:
* https://docs.google.com/spreadsheets/d/1BxiMVs0XRA5nFMdKvBdBZjgmUUqptlbs74OgvE2upms/edit
*/
function listMajors() {
gapi.client.sheets.spreadsheets.values.get({
spreadsheetId: '1BxiMVs0XRA5nFMdKvBdBZjgmUUqptlbs74OgvE2upms',
range: 'Class Data!A2:E',
}).then(function(response) {
var range = response.result;
if (range.values.length > 0) {
appendPre('Name, Major:');
for (i = 0; i < range.values.length; i ) {
var row = range.values[i];
// Print columns A and E, which correspond to indices 0 and 4.
appendPre(row[0] ', ' row[4]);
}
} else {
appendPre('No data found.');
}
}, function(response) {
appendPre('Error: ' response.result.error.message);
});
}
console.log('LOAD')
handleClientLoad()
}
})
</script>
</body>
</html>
Я попробовал несколько подходов, чтобы заставить это работать, ни один из которых не работает. Быстрый запуск кажется неправильным:https://developers.google.com/sheets/api/quickstart/js
Комментарии:
1. Где возникает ошибка в вашем скрипте?
2. Я считаю, что что-то здесь:
gapi.client.init
неправильно. Но мой код идентичен приведенному в примере.3. Спасибо за ответ. К сожалению, из вашего ответа я не могу понять вашу проблему. Это из-за моего плохого навыка. Я глубоко извиняюсь за это.
4. Можете ли вы подробно описать возникшую у вас ошибку, а также выполнили ли вы все шаги из быстрого запуска?
5. Есть какие-либо обновления по этому поводу? Такая же проблема