leo*_*tes 5 cors oauth-2.0 express google-oauth reactjs
我正在将 fetch 从 React 发送到 Express 以通过 Google 进行身份验证,但我的访问被 CORS 错误阻止。我将 POST 请求从 React 重定向到 Google URL 进行身份验证。我尝试在 Express 应用程序中使用 cors,但仍然遇到相同的错误。用于抓取
const handleClick = (e) => {
fetch('http://localhost:8000/api/mail/login', {
method: 'POST'
})
.then(res => res.text())
}
Run Code Online (Sandbox Code Playgroud)
在 Express app.js 中使用 cors
app.use(cors())
Run Code Online (Sandbox Code Playgroud)
尝试重定向到谷歌身份验证
const oauth2Client = new google.auth.OAuth2(
process.env.CLIENT_ID,
process.env.CLIENT_SECRET,
process.env.REDIRECT_URI
)
const url = oauth2Client.generateAuthUrl({
access_type: 'offline',
scope: process.env.SCOPE
})
const gmail = google.gmail({
version: 'v1',
auth: oauth2Client
})
router.post('/login', (req, res, next) => {
res.redirect(url)
})
Run Code Online (Sandbox Code Playgroud)
错误:访问“https://accounts.google.com/o/oauth2/v2/auth?access_type=offline&scope=https%3A%2F%2Fmail.google.com%2F&response_type=code&client_id=727520060136-ngpfd4ll798v42gfclh7cms9ndqstt32”进行获取。来自原点“http://localhost:3000”的 apps.googleusercontent.com&redirect_uri=http%3A%2F%2Flocalhost%3A8000'(从“http://localhost:8000/api/mail/login”重定向)已被阻止CORS 策略:请求的资源上不存在“Access-Control-Allow-Origin”标头。如果不透明响应满足您的需求,请将请求模式设置为“no-cors”以在禁用 CORS 的情况下获取资源。
Hei*_*ßen 12
身份验证流程必须发生在可见的浏览上下文中,而不是通过fetch请求进行。换句话说:您必须将当前选项卡导航到(或打开一个新选项卡)http://localhost:8000/api/mail/login,然后该选项卡将被重定向到https://accounts.google.com/ o/oauth2/v2/auth?...并且此页面变得可见。现在,用户必须与该页面交互以选择/确认他们的 Google 帐户,之后他们将被重定向到您服务器上的页面,并在 URL 中包含授权代码(例如,http://localhost:8000/callback?code =...) 并且您的服务器必须通过服务器到服务器调用交换访问令牌的授权代码。
这样发出的请求都不是跨源的,因此根本不会涉及 CORS。
handleClick您需要一个登录表单,而不是该功能,例如
<form action="http://localhost:8000/api/mail/login" method="post">
<input type="submit" value="Press to log in"/>
</form>
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
6433 次 |
| 最近记录: |