html 谷歌开放认证:尝试发出获取请求时,请求的资源上不存在“Access-Control-Allow-Origin”标头

wixjitnu  于 2022-12-16  发布在  其他
关注(0)|答案(1)|浏览(420)

所以我试着用passport google oauth20启用google认证,我创建了一个按钮,像这样把表单提交到后台。

<form className="auth-form" action ="/api/v1.0/authentication/google" method="get">
  <button type="submit" className="btn btn-light" >
    <img width="20px" style={{ marginBottom: "3px", marginRight: "1em" }} alt="Google sign-in" src="https://upload.wikimedia.org/wikipedia/commons/thumb/5/53/Google_%22G%22_Logo.svg/512px-Google_%22G%22_Logo.svg.png" />
    Sign up with Google
  </button>
</form>

但是这不允许我捕获get请求的响应,因此我尝试创建一个onClick函数,该函数调用一个向相同URL发出axios.get()请求的函数,如下所示

<div className="auth-form">
  <button className="btn btn-light" onClick={this.googleAuthenticate}>
    <img width="20px" style={{ marginBottom: "3px", marginRight: "1em" }} alt="Google sign-in" src="https://upload.wikimedia.org/wikipedia/commons/thumb/5/53/Google_%22G%22_Logo.svg/512px-Google_%22G%22_Logo.svg.png" />
    Sign up with Google
  </button>
</div>

这是我的类组件

class Register extends Component {
  constructor(props) {
    super(props);
    this.googleAuthenticate = this.googleAuthenticate.bind(this);
  }

  googleAuthenticate(){
    axios.get("/api/v1.0/authentication/google")
    .then(({data})=>{
      console.log("this is data",data);
    });
  }
}

但是这并没有把我重定向到谷歌签名页面,请给我一些建议该怎么做,当我点击按钮时得到的错误是
Access to XMLHttpRequest at 'https://accounts.google.com/o/oauth2/v2/auth? response_type=code&redirect_uri=http%3A%2F%2Flocalhost%3A3000%2Fapi%2Fv1.0%2Fgoogle%2Fcallback&scope=profile%20email&client_id=976971922840-p9eobg6v863nppicf7vsatfup1q82qjt.apps.googleusercontent.com' (redirected from 'http://localhost:3000/api/v1.0/authentication/google') from origin 'http://localhost:3000' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource.
服务器端代码为

router.get("/api/v1.0/authentication/google", restrict({ unregistered: 
true, registered: false }), passport.authenticate("google", { scope: 
["profile", "email"] }));

router.get("/api/v1.0/google/callback", restrict({ unregistered: true, registered: false }), passport.authenticate("google", { failureRedirect: "/register" }), (req, res,next) => {
    res.redirect("/");
});
elcex8rz

elcex8rz1#

我找到了解决办法:
[Passportjs][Angular5] No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'null' is therefore not allowed access
<a href="http://localhost:3000/login/google">Google</a>
其中“本地主机:3000/登录/谷歌”转到app.get('/login/google', passport.authenticate('google', { scope: ['profile','email']}) );

相关问题