我想在我的反应应用程序中使用Gmail API代表用户发送电子邮件。为此,我查看了此文档https://www.sitepoint.com/mastering-your-inbox-with-gmail-javascript-api/,并按如下方式实施:
当弹出谷歌登录窗口时,它会要求授权,在授予权限后,它会在我的控制台中记录未经授权。无论我使用哪个谷歌帐户登录,它都会发生。当我在控制台中记录auth结果时,它始终记录未定义。当我在Gmail中查看具有帐户访问权限的应用部分时,我可以在那里看到我的应用。现在可能出错的是我无法理解。除非我有用户,否则我无法继续前进。
App.js
var clientId = 'xxxxxxxxxxxx';
var API_KEY = 'xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx';
var scopes =
'https://www.googleapis.com/auth/gmail.readonly '+
'https://www.googleapis.com/auth/gmail.send';
class App extends Component {
constructor (props) {
super(props);
this.handleAuthClick = this.handleAuthClick.bind(this)
}
componentDidMount() {
this.handleClientLoad();
}
handleClientLoad = () => {
const script = document.createElement("script");
script.src = "https://apis.google.com/js/client.js";
script.async = true
script.onload = () => {
window.gapi.load('client', () => {
window.gapi.client.setApiKey(API_KEY);
window.setTimeout(this.checkAuth(), 1);
});
}
document.body.appendChild(script)
}
checkAuth() {
window.gapi.auth.authorize({
client_id: clientId,
scope: scopes,
immediate: true
}, () => this.handleAuthResult());
}
handleAuthClick() {
window.gapi.auth.authorize({
client_id: clientId,
scope: scopes,
immediate: false
}, () => this.handleAuthResult());
return false;
}
handleAuthResult(authResult) {
console.log(authResult);
if(authResult && !authResult.error) {
//success code
console.log("authorized");
} else {
//error code
console.log("unauthorized");
}
}
render() {
return (
<button onClick={this.handleAuthClick}>Authorize</button>
);
}
}