Привет, мое требование - отправить данные из формы реагирования и сохранить их в листе API Google. Для этого я пишу ниже код. Я создал свои учетные данные gapi и использую их.
import React, { Component } from 'react';
import gapi from 'gapi-client';
import { Form, Text } from 'informed';
const SPREADSHEET_ID = '1APT_vtl6wUbIpJFKnVFId8WaMCpUKY1k6BNvCj2SVAU'; //from the URL of your blank Google Sheet
const CLIENT_ID = '892818296916-934g40dnmvecddhcqa2ctouda6pfp9np.apps.googleusercontent.com'; //from https://console.developers.google.com/apis/credentials
const API_KEY = 'AIzaSyCWC8w6oTTLC8d9cAePjfL1Raii1oe2YHc'; //https://console.developers.google.com/apis/credentials
const SCOPE = 'https://www.googleapis.com/auth/spreadsheets';
class TestForm extends Component {
constructor(props) {
super(props);
this.handleSubmit = this.handleSubmit.bind(this);
}
componentDidMount() { //called automatically by React
this.handleClientLoad();
}
handleClientLoad = () => { //initialize the Google API
gapi.load('client:auth2', this.initClient);
}
initClient = () => { //provide the authentication credentials you set up in the Google developer console
gapi.client.init({
'apiKey': API_KEY,
'clientId': CLIENT_ID,
'scope': SCOPE,
'discoveryDocs': ['https://sheets.googleapis.com/$discovery/rest?version=v4'],
}).then(() => {
console.log('do something')
// gapi.auth2.getAuthInstance().isSignedIn.listen(this.updateSignInStatus); //add a function called `updateSignInStatus` if you want to do something once a user is logged in with Google
// this.updateSignInStatus(gapi.auth2.getAuthInstance().isSignedIn.get());
});
}
handleSubmit(submissionValues) {
console.log('A name was submitted: ');
const params = {
// The ID of the spreadsheet to update.
spreadsheetId: SPREADSHEET_ID,
// The A1 notation of a range to search for a logical table of data.Values will be appended after the last row of the table.
range: 'Sheet1', //this is the default spreadsheet name, so unless you've changed it, or are submitting to multiple sheets, you can leave this
// How the input data should be interpreted.
valueInputOption: 'RAW', //RAW = if no conversion or formatting of submitted data is needed. Otherwise USER_ENTERED
// How the input data should be inserted.
insertDataOption: 'INSERT_ROWS', //Choose OVERWRITE OR INSERT_ROWS
};
const valueRangeBody = {
'majorDimension': 'ROWS', //log each entry as a new row (vs column)
'values': [submissionValues] //convert the object's values to an array
};
console.log('valueRangeBody' + JSON.stringify(valueRangeBody))
let request = gapi.client.sheets.spreadsheets.values.append(params, valueRangeBody);
console.log('request' + JSON.stringify(request))
request.then(function (response) {
console.log('dinshaw')
// TODO: Insert desired response behaviour on submission
console.log(response.result);
}, function (reason) {
console.log('123')
console.error('error: ' + reason.result.error.message);
});
console.log('values' + gapi.client)
}
render() {
return (
<Form
onSubmit={this.handleSubmit}
>
<label>
Name:
<Text field='Name' />
</label>
<label>
Number:
<Text field='Number' />
</label>
<button type='submit'>
Submit
</button>
</Form>
);
}
}
export default TestForm;
Но я получаю сообщение об ошибке на консоли при отправке.
cb=gapi.loaded_0:220 POST https://content-sheets.googleapis.com/v4/spreadsheets/1APT_vtl6wUbIpJFKnVFId8WaMCpUKY1k6BNvCj2SVAU/values/Sheet1:append?insertDataOption=INSERT_ROWS&valueInputOption=RAW&alt=json&key=AIzaSyCWC8w6oTTLC8d9cAePjfL1Raii1oe2YHc 401
В запросе я отправляю эти данные
request{"Cf":1,"Nb":{"Nf":null,"wh":{"path":"/v4/spreadsheets/1APT_vtl6wUbIpJFKnVFId8WaMCpUKY1k6BNvCj2SVAU/values/Sheet1:append","method":"POST","params":{"insertDataOption":"INSERT_ROWS","valueInputOption":"RAW"},"headers":{},"body":{"majorDimension":"ROWS","values":[{"Name":"Dinshaw Raje","Number":"111"}]},"root":"https://sheets.googleapis.com","apiId":"sheets:v4"},"Op":"auto","oZ":false,"vN":false}}
вот скриншот консоли
Пожалуйста, помогите мне в решении этого. Заранее спасибо.