javascript - 在 ReactJS 中实现简单的 Google oAuth
问题描述
我有一个像这样设置的迷你香草 JS 应用程序:
<!DOCTYPE html>
<html lang="en">
<head>
<script src="https://apis.google.com/js/platform.js" async defer></script>
<meta
name="google-signin-client_id"
content="{{client_id}}" /> <!--Here goes my actual WORKING google client id-->
/>
</head>
<body>
<div class="g-signin2" data-onsuccess="onSignIn"></div>
<button onclick="signOut()">Sign Out</button>
<script>
function onSignIn(googleUser) {
const profile = googleUser.getBasicProfile();
console.log("ID: " + profile.getId()); // Do not send to your backend! Use an ID token instead.
console.log("Name: " + profile.getName());
console.log("Image URL: " + profile.getImageUrl());
console.log("Email: " + profile.getEmail()); // This is null if the 'email' scope is not present.
}
function signOut() {
var auth2 = gapi.auth2.getAuthInstance();
auth2.signOut().then(function () {
console.log("User signed out.");
});
}
</script>
</body>
</html>
我在哪里登录用户,然后我可以使用 Google 将其注销。当我尝试将其转移到 React 项目时,我遇到了一些问题:
- 无法像在 VanillaJS 应用程序中那样执行函数(在引号之间)
- 即使我
public/index.html
在 React 项目中包含脚本标签,我也无权访问该gapi
变量。有谁知道如何做到这一点?
解决方案
我认为您可以使用此库https://www.npmjs.com/package/react-google-login。或者,也许您可以阅读该 repo 的 github 以了解如何获取 google oauth 以响应应用程序
推荐阅读
- javascript - 如何在 javascript 的“文本冒险”中将图像插入到此文本元素中?
- r - tsoutliers 和使用替换
- r - 提取列表名称作为 R 中的字符串传递给函数
- c# - 比较字符串中的对象属性
- java - 如何为 TriangleMesh 中的一些三角形着色?
- python - 使用 pytest 进行模拟时出现 ModuleNotFoundError
- salesforce - 如何在出站更改集中将表数据从 SandBox 传输到生产环境?
- python - Apache Beam(2.32.0) 安装失败
- c - 试图制作一个反向循环单链表,其中每个节点都添加到列表的前面,但所有后续节点都丢失了
- mariadb - MariaDB 安装后无法启动