Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/angular/26.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/vim/5.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Node.js 由于CORS策略,对google oAuth的角度请求失败_Node.js_Angular_Cors_Xmlhttprequest_Google Oauth - Fatal编程技术网

Node.js 由于CORS策略,对google oAuth的角度请求失败

Node.js 由于CORS策略,对google oAuth的角度请求失败,node.js,angular,cors,xmlhttprequest,google-oauth,Node.js,Angular,Cors,Xmlhttprequest,Google Oauth,我已经用google身份验证设置了angular/nodejs(express)应用程序,但每当我通过angular应用程序请求google oauth时,它就会抛出cors错误,但如果我直接从浏览器请求,它就会正常工作 后端在端口3000上运行,angular在4200上运行 我正在使用cors包来允许server.js中的所有cors请求: app.use(passport.initialize()); // Passport Config require('./config/passpo

我已经用google身份验证设置了angular/nodejs(express)应用程序,但每当我通过angular应用程序请求google oauth时,它就会抛出cors错误,但如果我直接从浏览器请求,它就会正常工作

后端在端口3000上运行,angular在4200上运行

我正在使用
cors
包来允许server.js中的所有cors请求:

app.use(passport.initialize());

// Passport Config
require('./config/passport')(passport);

// Allowing all cors requests
app.use(cors());
app.use(express.static(path.join(__dirname, 'public')));

app.use('/users', usersRouter);
app.use('/auth', authRouter);
Passport配置:

passport.use(
    new GoogleStrategy(
        keys,
        (token, refreshToken, profile, done) => {
            process.nextTick(() => {
                User.findOne({ email: email })
                    .then(user => {
                        if (user) {
                            return done(null, user);
                        }
                    })
                    .catch(err => console.log(err));
            });
        }
    )
);
这是谷歌认证路径:

router.get('/google', passport.authenticate('google', {
        scope: ['profile', 'email'],
        session: false
    }),
    (req, res) => {
        // Create JWT payload
        const payload = {
            id: req.user.id,
            email: req.user.email
        };

        jwt.sign(payload, secret, expires, (err, token) => {
            res.json(token);
        });
    }
);
这是我的要求:

googleAuth() {
    return this.http.get<any>('http://localhost:3000/auth/google').pipe(
        map(user => {
            if (user) {
                localStorage.setItem(
                    'currentUser',
                    JSON.stringify(user)
                );
            }

            return user;
        })
    );
}
我还授权了google开发者控制台中的JavaScript源代码:


我对angular和nodejs非常陌生,我读过所有类似的问题,但找不到解决这个问题的方法。

试试这种直接调用URL的方法:(如果我在语法上遗漏了一些东西,请原谅,但基本上这就是我的想法)

googleAuth(){
 window.open('/google',"mywindow","location=1,status=1,scrollbars=1, width=800,height=800");
let listener = window.addEventListener('message', (message) => {
  //message will contain google user and details
});

}
在服务器中,我假设您已经设置了passport策略

router.get('/google', passport.authenticate('google', {
        scope: ['profile', 'email'],
        session: false } ))

router.get('/google/callback',
    passport.authenticate('google', { failureRedirect: '/auth/fail' }),
function(req, res) {
    var responseHTML = '<html><head><title>Main</title></head><body></body><script>res = %value%; window.opener.postMessage(res, "*");window.close();</script></html>'
    responseHTML = responseHTML.replace('%value%', JSON.stringify({
        user: req.user
    }));
    res.status(200).send(responseHTML);


});
router.get('/google',passport.authenticate('google',){
范围:['profile','email'],
会话:false})
router.get(“/google/callback”,
authenticate('google',{failureRedirect:'/auth/fail'}),
功能(req、res){
var responseHTML='Mainres=%value%;window.opener.postMessage(res,“*”);window.close();'
responseHTML=responseHTML.replace(“%value%”,JSON.stringify({
用户:req.user
}));
res.status(200).发送(responseHTML);
});
有帮助吗?
router.get('/google', passport.authenticate('google', {
        scope: ['profile', 'email'],
        session: false } ))

router.get('/google/callback',
    passport.authenticate('google', { failureRedirect: '/auth/fail' }),
function(req, res) {
    var responseHTML = '<html><head><title>Main</title></head><body></body><script>res = %value%; window.opener.postMessage(res, "*");window.close();</script></html>'
    responseHTML = responseHTML.replace('%value%', JSON.stringify({
        user: req.user
    }));
    res.status(200).send(responseHTML);


});