我正在构建一个简单的应用程序,其中 React 作为前端,Node/Express/MongoDB 作为后端。我正在使用 Passport 对用户进行身份验证。本地身份验证以及 Google 身份验证都在工作。
我似乎无法通过应用程序加载谷歌登录页面。我收到 CORS 错误。我在下面分享了错误。
在反应登录页面上:
const onClick = async () => {
await Axios.get('/auth/google');
};
代理中间件:
const { createProxyMiddleware } = require('http-proxy-middleware');
module.exports = function (app) {
app.use(createProxyMiddleware('/auth', { target: 'http://localhost:4000' }));
};
节点服务器.js:
app.use('/auth', require('./routes/auth'));
路由/身份验证文件:
const cors = require('cors');
var corsOptions = {
origin: 'http://localhost:3000',
methods: 'GET,HEAD,PUT,PATCH,POST,DELETE',
preflightContinue: false,
optionsSuccessStatus: 204,
};
router.get(
'/google',
cors(corsOptions),
passport.authenticate('google', {
scope: ['profile', 'email'],
}),
);
router.get('/google/redirect',cors(corsOptions), passport.authenticate('google'), (req, res) => {
res.send(req.user);
});
护照配置.js:
passport.use(
new GoogleStrategy(
{
clientID: ClientID,
clientSecret: ClientSecret,
callbackURL: '/auth/google/redirect',
proxy: true,
},
(accessToken, refreshToken, profile, done) => {
// passport callback function
//check if user already exists in our db with the given profile ID
User.findOne({ googleId: profile.id }).then((currentUser) => {
if (currentUser) {
//if we already have a record with the given profile ID
done(null, currentUser);
} else {
//if not, create a new user
new User({
googleId: profile.id,
})
.save()
.then((newUser) => {
done(null, newUser);
});
}
});
},
),
);
错误:
Access to XMLHttpRequest at 'https://accounts.google.com/o/oauth2/v2/auth?response_type=code&redirect_uri=http%3A%2F%2Flocalhost%3A3000%2Fauth%2Fgoogle%2Fredirect&scope=profile%20email&client_id=<clientID>.apps.googleusercontent.com' (redirected from 'http://localhost:3000/auth/google') from origin 'http://localhost:3000' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource.
如果我单击上面的 XMLHttpRequest 链接,我就可以进行身份验证,并在我的数据库上使用 googleID 创建一个帐户。
我尝试了整个互联网上建议的不同选项,但没有一个对我有用。我不确定这里出了什么问题。