请求被CORS阻止

时间:2019-03-31 23:05:31

标签: node.js reactjs heroku cors google-oauth

我正在尝试在我的应用程序中实施passportjs google策略,并且成功在本地服务器上执行了该策略。但是,在部署heroku时,我的请求被CORB阻止。

这是登录组件的外观:

<button className="btn btn-danger" onClick={this.handleAuth}>
<i className="fab fa-2x fa-google" />
</button>
handleAuth = async event => {
    event.preventDefault();
    console.log("G button clicked");
    let res = await fetch("/auth/google", {
      method: "GET",
      mode: "no-cors"
    });
    let data = await res.json();
    console.log(data);
  };

这是服务器的外观:

var cors = require("cors");
// app.use(cors());
app.use("*", function(req, res, next) {
  //replace localhost:8080 to the ip address:port of your server
  res.header("Access-Control-Allow-Origin", "*");
  res.header("Access-Control-Allow-Headers", "X-Requested-With");
  res.header("Access-Control-Allow-Headers", "Content-Type");
  res.header("Access-Control-Allow-Credentials", true);
  next();
});

//enable pre-flight
app.options("*", cors());

身份验证路线:

router.get("/google", googleauth);

//auth callback from google
router.get("/google/redirect", passport.authenticate("google"), (req, res) => {
  if (process.env.NODE_ENV === "production")
    // For Heroku
    res.redirect("https://birdiez.herokuapp.com/dash");

  else res.redirect("http://localhost:3000/dash");
});

链接到我的Heroku应用程序:https://birdiez.herokuapp.com/signup

但是,当我按下按钮(与Google继续)时,我没有在控制台上看到此消息,而是重定向到Google同意屏幕:

Signup.js:38 
Cross-Origin Read Blocking (CORB) blocked cross-origin response 
https://accounts.google.com/o/oauth2/v2/auth?response_type=code&redirect_uri=http%3A%2F%2Fbirdiez.herokuapp.com%2Fauth%2Fgoogle%2Fredirect&scope=Email&client_id=928268479235-8v8jpc93n6fo7b3j01hl7tqj366hfo2v.apps.googleusercontent.com with MIME type text/html. 
See https://www.chromestatus.com/feature/5629709824032768 for more details.

但是,当我单击控制台中显示的链接时,我得到了Google同意屏幕。 我不知道我在这里想念的是什么。

注意:我已经从客户端的./src/index.js中删除了服务工作者

链接到github repo:(工作分支是exp) https://github.com/Arjunalapsapkota/Birdie

1 个答案:

答案 0 :(得分:0)

这些设置对我有用。

app.use(function(req, res, next) {
        res.header("Access-Control-Allow-Origin", "*");
        res.header("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept");
        res.header('Access-Control-Allow-Methods', 'PUT, POST, GET, DELETE, OPTIONS');
    if (req.method === 'OPTIONS') {
            return res.status(200).send('ok');
        }
        else {
            next();
        }
});