与Passport一起使用获取将获得“在所请求的资源上不存在“ Access-Control-Allow-Origin”报头”。 [英] Using fetch with Passport gets "No 'Access-Control-Allow-Origin' header is present on the requested resource."

查看:58
本文介绍了与Passport一起使用获取将获得“在所请求的资源上不存在“ Access-Control-Allow-Origin”报头”。的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试在我的网站上放置一个按钮,该按钮将允许用户授权访问其YouTube帐户。我正在使用Passport进行身份验证。我的代码正在使用访存发送请求。当我单击该按钮时,我得到:

I am trying to put a button on my website which will let the user authorize access to his YouTube account. I am using Passport for the authentication. My code is using fetch to send the request. When I click on the button, I get:


访问
的权限'https://accounts.google.com/o/oauth2 /auth?access_type=offline&approval_prompt=force&response_type=code&redirect_uri=http%3A%2F%2Flocalhost%3A3000%2Fgooglecb&scope=https%3A%2F%2Fwww.googleapis.com%2Fauth%2Fyoutube&client_id=。 ..'原点
'http:// localhost:3000'的
(从'http:// localhost:3000 / google'重定向)已被CORS政策阻止:对
的响应预检请求未通过访问控制检查:在请求的
资源上不存在
'Access-Control-Allow-Origin'标头。如果不透明的响应满足您的需求,请将请求的
模式设置为 no-cors,以在禁用CORS的情况下获取资源。

Access to fetch at 'https://accounts.google.com/o/oauth2/auth?access_type=offline&approval_prompt=force&response_type=code&redirect_uri=http%3A%2F%2Flocalhost%3A3000%2Fgooglecb&scope=https%3A%2F%2Fwww.googleapis.com%2Fauth%2Fyoutube&client_id=...' (redirected from 'http://localhost:3000/google') from origin 'http://localhost:3000' has been blocked by CORS policy: Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource. If an opaque response serves your needs, set the request's mode to 'no-cors' to fetch the resource with CORS disabled.

如果我使用href来/ google它起作用。

If I use an href to /google it works.

app.js:

const appConfig = require('./config.js');
const cors = require('cors')
const express = require('express');
const passport = require('passport');
const path = require('path');
const YoutubeV3Strategy = require('passport-youtube-v3').Strategy;

const index = require('./routes/index');

const app = express();

app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'ejs');

app.use(cors());

app.use(passport.initialize());
app.use(passport.session());

passport.use(new YoutubeV3Strategy({
  clientID: appConfig.youtube.id,
  clientSecret: appConfig.youtube.secret,
  callbackURL: 'http://localhost:3000/googlecb',
  scope: ['https://www.googleapis.com/auth/youtube'],
},
function (accessToken, refreshToken, profile, cb) {
  const user = {
    accessToken: accessToken,
    refreshToken: refreshToken,
    profile: profile,
  };
  return cb(null, user);
}));

passport.serializeUser((user, cb) => {
  cb(null, user);
});

passport.deserializeUser((obj, cb) => {
  cb(null, obj);
});

app.use('/', index);

app.use(function(req, res, next) {
  var err = new Error('Not Found');
  err.status = 404;
  next(err);
});

app.use(function(err, req, res, next) {
  res.locals.message = err.message;
  res.locals.error = req.app.get('env') === 'development' ? err : {};
  res.status(err.status || 500);
  res.render('error');
});

module.exports = app;

index.js:

const express = require('express');
const passport = require('passport');

const router = express.Router();

router.get('/', function(req, res, next) {
  res.render('index');
});

router.get('/google', async (req, res) => {
  passport.authenticate('youtube')(req, res, () => res.send('ok'));
});

router.get('/googlecb', passport.authenticate('youtube'), async (req, res) => {
  const name = req.user.profile.displayName;
  console.log('googlecb name: ' + name);
  return res.send(req.user);
});

module.exports = router;

index.ejs:

index.ejs:

<!DOCTYPE html>
<html>
  <head>
  </head>
  <body>
    <p><button id="auth" onclick="go()">Authorize</button><p>
    <p><a href="/google">Authorize</a><p>
    <script> 
async function go() {
  console.log('go');
  await fetch('/google',
    {
      method: 'GET',
      headers: {
        'Content-Type': 'application/json',
      },
    },
  )
  .then(response => {
    console.log('response');
    return response.json();
  })
  .then(data => {
    console.log('data');
  });
}
    </script>
  </body>
</html>


推荐答案

好的,这是Passport的未解决问题:

OK this is an open issue with Passport:

https://github.com/jaredhanson / passport / issues / 582#issuecomment-506283986

我应该使用href而不是提取。

I should use the href and not fetch.

可能的副本

当从React前端向后端的Google Oauth PassportJS发送请求时,Cors错误

这篇关于与Passport一起使用获取将获得“在所请求的资源上不存在“ Access-Control-Allow-Origin”报头”。的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆