我正在构建一个包含日历的小型MERN堆栈应用程序。该日历的目的是将其与多个员工的谷歌日历同步,以便安排日程。
我已经开始测试Google Calendar API,当我直接使用Node运行它时,他们的测试代码工作正常:https://developers.google.com/calendar/api/quickstart/nodejs
然而,现在我正在尝试配置一个按钮,该按钮将触发从React到Express后端的请求,并点击一条路线(并使用后续的回调路线),以便授权员工(操作员)的工作谷歌帐户,并获取存储在数据库中的必要凭据。通过这种方式,应用程序可以保存每个操作员所需的身份验证和刷新令牌,以保持谷歌日历与应用程序的日历持续同步。这似乎不起作用,至少在我处于开发阶段时,出于某种原因,我一直收到这样的错误:
在“”处获取的访问权限(从“”重定向http://localhost:3500/api/auth/')来自原点'http://localhost:3000'已被CORS策略阻止:对飞行前请求的响应未通过访问控制检查:请求的资源上不存在“access control Allow Origin”标头。如果不透明的响应满足您的需求,请将请求的模式设置为“no cors”,以在cors被禁用的情况下获取资源。
我曾想过在前端完成这一切,并从那里将其发送到我的数据库,但这似乎不安全。
我建立了cors,我有http://localhost:3000'列为允许的来源,它适用于除此之外的所有其他内容。
我也尝试过使用代理,但我似乎无法让我的前端使用它。我尝试过http代理中间件包,我尝试过简单地添加“代理”:“http://localhost:3500“到我的package.json。这一切都不需要,控制台在我的服务器上记录请求源显示它们仍然来自localhost:3000。
我已经为此辛苦了一段时间了,我似乎无法克服它。
这是来自apiSlice的查询生成器(这在路由被明确调用时起作用。我认为问题实际上可能是我从auth重定向中得到的结果?):
` getOperatorAuth: builder.query({ query: (operatorEmail) => ({ url:`/api/auth/${operatorEmail}`, validateStatus: (response, result) => { return response.status === 200 && !result.isError }, }), ` Here are the routes: `const express = require('express') const router = express.Router() const operatorsController = require('../controllers/operatorsController') router.route('/auth/:operatorEmail') .get(operatorsController.getGoogleAuth) router.route('/callback') .get(operatorsController.getGoogleAuthCallback) module.exports = router` And here are the functions they call: `const getGoogleAuth = async (req, res) => { console.log(req.headers.origin) console.log("requesting auth route") const operatorEmail = req.params.operatorEmail; const oAuth2Client = new OAuth2Client(clientId, clientSecret, redirectUri); const authorizeUrl = oAuth2Client.generateAuthUrl({ access_type: 'offline', scope: ['https://www.googleapis.com/auth/calendar'], state: JSON.stringify({ operatorEmail }), }); res.redirect(authorizeUrl); } const getGoogleAuthCallback =async (req, res) => { console.log("google callback") const code = req.query.code; const state = JSON.parse(decodeURIComponent(req.query.state)); const operatorEmail = state.operatorEmail; const data = querystring.stringify({ code: code, client_id: clientId, client_secret: clientSecret, redirect_uri: redirectUri, grant_type: 'authorization_code' }); const headers = { 'Content-Type': 'application/x-www-form-urlencoded' }; try { const response = await axios.post( 'https://oauth2.googleapis.com/token', data, { headers: headers } ); const accessToken = response.data.access_token; const refreshToken = response.data.refresh_token; // Store the access token and refresh token in MongoDB const operatorAuth = new OperatorAuth({ email: operatorEmail, accessToken: accessToken, refreshToken: refreshToken }); await operatorAuth.save(); res.send('Access token and refresh token received and stored'); } catch (error) { res.send(error.message); } }`