尝试获取资源Passport ReactJS和ExpressJS时出现NetworkError:CORS

时间:2020-09-24 07:28:07

标签: node.js reactjs express cors passport.js

我有一个使用React JS(http:// localhost:3000 /)开发的前端,而我的后端是使用Express JS(http:// localhost:5000 /)

Google控制台详细信息

“ React Login”页面:单击使用Google的登录名

  const _handleGoogleSignInClick = async () => {
        window.open("http://localhost:5000/socialauth/google", "_self");
    }

快递代码

app.use(express.json());
app.use(cookieSession({
    name: "session",
    maxAge: 24 * 60 * 60 * 1000,
    keys:[keys.session.cookieKey]
}))

app.use(cookieParser());
app.use(passport.initialize());
app.use(passport.session());
app.use(
    cors({
      origin: "http://localhost:3000",
      methods: "GET,HEAD,PUT,PATCH,POST,DELETE",
      credentials: true
    })
  );

//routes
app.use(cors());
app.use("/auth", require("./routes/jwtAuth"));
app.use("/socialauth", socialAuth);

********************************************************
const CLIENT_HOME_PAGE_URL = "http://localhost:3000";

router.get('/google', passport.authenticate('google', { scope: ["profile"] }));
router.get('/google/callback', passport.authenticate('google', {
    successRedirect: CLIENT_HOME_PAGE_URL,
    failureRedirect: "/socialauth/login/failed"
}));

router.get("/login/success", (req, res) => {
    console.log(req.user);
    if (req.user) {
        res.json({ true});
    }
});

现在,我已经成功从Google验证了用户身份,password JS为用户创建了一个会话,并将用户重定向到前端,在此他们又必须再次验证自己。此时,前端尝试验证用户,服务器成功验证用户并返回true,但是前端无法捕获。因此,用户无法看到仪表板,因为状态为假...

fetch("http://localhost:5000/socialauth/login/success", {
          method: "GET",
          credentials: "include",
          headers: {
            Accept: "application/json",
            "Content-Type": "application/json",
            "Access-Control-Allow-Credentials": true
          }
        })
          .then(response => {
            if (response.status === 200) return response.json();
            throw new Error("failed to authenticate user");
          })
          .then(responseJson => {
            console.log("responseJson is -====", responseJson);
            setIsAuthenticated(true);

问题?

从客户端访问fetch(“ http:// localhost:5000 / socialauth / login / success”时,我看到服务器可以成功识别用户并返回true,但是在我的客户端上我无法获取JSON响应。

错误详情

错误为-====尝试获取资源时发生TypeError:NetworkError。 DesktopComponent.js:62 跨域请求被阻止:“相同来源策略”不允许读取“ http:// localhost:5000 / socialauth / login / success”上的远程资源。 (原因:如果CORS标头“ Access-Control-Allow-Origin”为“ *”,则不支持凭据)

1 个答案:

答案 0 :(得分:0)

编辑:问题是app.use(cors())覆盖了

app.use(
    cors({
      origin: "http://localhost:3000",
      methods: "GET,HEAD,PUT,PATCH,POST,DELETE",
      credentials: true
    })
  )

将CORS与凭据配合使用时必不可少

您可以参考CORS credentials

这基本上是因为您的客户端正在发送带有withCredentials的请求,因此您需要将其设置为false(或者在服务器端更改Access-Control-Allow-Origin