为了账号安全,请及时绑定邮箱和手机立即绑定

将 fetch 与 Passport 结合使用会得到“请求的资源上不存在

将 fetch 与 Passport 结合使用会得到“请求的资源上不存在

精慕HU 2023-02-17 10:28:23
我想在我的网站上放置一个按钮,让用户授权访问他的 YouTube 帐户。我正在使用 Passport 进行身份验证。我的代码使用 fetch 来发送请求。当我点击按钮时,我得到:访问“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/google'重定向)来自'http://localhost:3000'已被CORS策略阻止:对预检请求的响应不'未通过访问控制检查:请求的资源上不存在“Access-Control-Allow-Origin”标头。如果不透明的响应满足您的需求,请将请求的模式设置为“no-cors”以在禁用 CORS 的情况下获取资源。如果我对 /google 使用 href,它就可以工作。应用程序.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;
查看完整描述

2 回答

?
沧海一幻觉

TA贡献1824条经验 获得超5个赞

查看完整回答
反对 回复 2023-02-17
?
慕标琳琳

TA贡献1830条经验 获得超9个赞

解决方案是为此使用带有后端路由 url 的锚标记。就像你已经this.router.get("/auth/google", passport.authenticate("google", { scope: ["email", "profile"], successRedirect: "http://localhost:3000" }));<a href="localhost:3000/auth/google>Click me</a>



查看完整回答
反对 回复 2023-02-17
  • 2 回答
  • 0 关注
  • 164 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
微信客服

购课补贴
联系客服咨询优惠详情

帮助反馈 APP下载

慕课网APP
您的移动学习伙伴

公众号

扫描二维码
关注慕课网微信公众号