微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

即使在React / Node / Passport上为Google身份验证添加了CORS选项后,仍然面临CORS错误

如何解决即使在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);
});

passportconfig.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创建一个帐户。

我尝试了整个互联网上建议的其他选择,但是没有一个我有用。我不确定这里出了什么问题。

解决方法

根据documentation,请尝试完全删除corsOptions,并在声明任何路由器之前,在您的快速中间件中使用cors()函数。像这样:

app.use(cors());

让我知道这是否可行。

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐


Selenium Web驱动程序和Java。元素在(x,y)点处不可单击。其他元素将获得点击?
Python-如何使用点“。” 访问字典成员?
Java 字符串是不可变的。到底是什么意思?
Java中的“ final”关键字如何工作?(我仍然可以修改对象。)
“loop:”在Java代码中。这是什么,为什么要编译?
java.lang.ClassNotFoundException:sun.jdbc.odbc.JdbcOdbcDriver发生异常。为什么?
这是用Java进行XML解析的最佳库。
Java的PriorityQueue的内置迭代器不会以任何特定顺序遍历数据结构。为什么?
如何在Java中聆听按键时移动图像。
Java“Program to an interface”。这是什么意思?