簡體   English   中英

Google OAuth:嘗試發出獲取請求時,請求的資源上不存在“Access-Control-Allow-Origin”標頭

[英]Google OAuth : No 'Access-Control-Allow-Origin' header is present on the requested resource when trying to make get request

所以我正在嘗試使用 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("/");
});

我找到了一個解決方案:

[Passportjs][Angular5] 請求的資源上不存在“Access-Control-Allow-Origin”標頭。 因此不允許訪問 Origin 'null'

<a href="http://localhost:3000/login/google">Google</a>

其中“localhost:3000/login/google”轉到app.get('/login/google', passport.authenticate('google', { scope: ['profile','email']}) );

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM