如何解决即使在React / Node / Passport上为Google身份验证添加了CORS选项后,仍然面临CORS错误
我正在构建一个简单的应用程序,其中将React作为前端,将Node / Express / MongoDB作为后端。我正在使用Passport验证用户身份。本地身份验证以及Google身份验证都可以正常工作。
我似乎无法通过该应用加载Google登录页面。我收到CORS错误。我已经分享了以下错误。
在React Login页面上:
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' }));
};
Node Server.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',passport.authenticate('google'),(req,res) => {
res.send(req.user);
});
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创建一个帐户。
我尝试了整个互联网上建议的其他选择,但是没有一个对我有用。我不确定这里出了什么问题。
解决方法
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。