【问题标题】:having CORS problem despite having all those settings in Express and React [closed]尽管在 Express 和 React 中有所有这些设置,但仍有 CORS 问题 [关闭]
【发布时间】:2021-05-08 22:39:52
【问题描述】:

我需要使用带有 Passport Js 的 Google oauth2 进行身份验证才能获取用户的电子邮件,尽管在后端设置了 CORS 并在 Axios 中设置了“允许来源”,但我仍然收到此错误:

**`Access to XMLHttpRequest at 'https://accounts.google.com/o/oauth2/v2/auth?response_type=code&redirect_uri=http%3A%2F%2F127.0.0.1%3A3001%2Fauth%2Fgoogle%2Fcallback&scope=email%20profile&client_id=460885025919-52uoa7aj99a7euei6s5c88otv2jh25m9.apps.googleusercontent.com' (redirected from 'http://127.0.0.1:3001/auth/google') from origin 'http://127.0.0.1:3000' has been blocked by CORS policy: Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource.`**

我该怎么办?

我找了3天没找到答案!

我的后台app.js

const express = require("express");
const cors = require("cors");
const fs = require("fs");
const https = require("https");

const passport = require("passport");
const GoogleStrategy = require("passport-google-oauth20").Strategy;
const session = require("express-session");

const env = require("./essentials.json");

const loginPage = require("./routes/login");
const registrationPage = require("./routes/registration");
const { authenticated } = require("./routes/socialMediaRegistration");
const socialMediaRegistration = require("./routes/socialMediaRegistration");

const app = express();

app.use(express.json());
app.use(express.urlencoded({ extended: true }));

const corsOptions = {
  origin: ["http://127.0.0.1:3000"],
  credentials: true,
  optionSuccessStatus: 200,
  preflightContinue: false,
  allowedHeaders: ["*"],
  exposedHeaders: ["*"],
  methods: "GET,HEAD,PUT,PATCH,POST,DELETE,OPTIONS",
};
app.use(cors(corsOptions));

//route handlers
app.use("/login", loginPage);
app.use("/registration", registrationPage);
// app.use("/auth", cors(), socialMediaRegistration);

/////////////////////////////////

app.use(passport.initialize());
app.use(passport.session());

/////////////////////////////////

app.get("/", (req, res) => {
  res.sendStatus(200).send("done");
});

passport.use(
  new GoogleStrategy(
    {
      clientID: env.GOOGLE_CLIENT_ID,
      clientSecret: env.GOOGLE_CLIENT_SECRET,
      callbackURL: "http://127.0.0.1:3001/auth/google/callback",
      passReqToCallback: true,
    },
    (accessToken, refreshToken, profile, cb) => {
      return cb(null, profile);
    }
  )
);

passport.serializeUser((user, cb) => {
  cb(null, user);
});

passport.deserializeUser((obj, cb) => {
  cb(null, obj);
});

app.use(
  session({
    secret: "hooooo",
    resave: false,
    saveUninitialized: false,
  })
);

app.use(passport.initialize());
app.use(passport.session());

app.get(
  "/auth/google",
  cors(corsOptions),
  passport.authenticate("google", { scope: ["email", "profile"] })
);

app.get(
  "/auth/google/callback",
  cors(corsOptions),
  passport.authenticate(
    "google",
    {
      successRedirect:
        "http://localhost:3000/registration/social-media/password",
    },
    (req, res) => {
      res.header("Access-Control-Allow-Origin", "*");
      res.json({ user: "sobhanessi" });
    }
  )
);

const port = process.env.PORT || 3001;

// https
//   .createServer(
//     {
//       key: fs.readFileSync("server.key"),
//       cert: fs.readFileSync("server.cert"),
//     },
//     app
//   )
//   .listen(port, () => console.log(`https://localhost:${port}`));

app.listen(port, () => console.log(`http://127.0.0.1:${port}`));

这是我的frontend 页面


    import React, { Component } from "react";
    import Joi from "joi-browser";
    import axios from "axios";
    import Form from "./common/form.jsx";
    import Input from "./common/input.jsx";
    
    class LoginPage extends Form {
      state = {
        data: { email: "", password: "" },
        errors: {},
      };
    
      schema = {
        email: Joi.string().required(),
        password: Joi.string().required(),
      };
      handleFacebook = async (e) => {
        e.preventDefault();
        const result = await axios.get(
          "https://localhost:3001/auth/facebook",
          { crossDomain: true },
          {
            headers: {
              "Access-Control-Allow-Headers": "http://localhost:3000",
              "Content-Type": "text/plain",
            },
          }
        );
        result.then(() => {
          console.log("man click shodam ");
          this.props.history.push("/registration/social-media/password");
        });
        // .catch((err) =>
        //   this.props.history.push("/registration/login",)
        // );
      };
      handleGoogle = async () => {
        const headers = {
          headers: {
            "Access-Control-Allow-Origin": "http://127.0.0.1:3000",
            "Content-Type": "application/x-www-form-urlencoded;charset=utf-8",
            "Access-Control-Allow-Methods": "GET,PUT,POST,DELETE,PATCH,OPTIONS",
            "Access-Control-Allow-Credentials": true,
          },
        };
        await axios
          .get("http://127.0.0.1:3001/auth/google", headers)
          .then((result) =>
            this.props.history.push("/registration/social-media/password")
          );
        // .catch((err) =>
        //   this.props.history.push("/registration/login")
        // );
      };
    
      render() {
        let { data, errors } = this.state;
        return (
          <React.Fragment>
            <form onSubmit={this.handleSubmit}>
              <Input
                name="email"
                label="Email"
                onChange={this.handleChange}
                value={data.email}
                error={errors["email"]}
              />
              <Input
                name="password"
                label="Password"
                onChange={this.handleChange}
                value={data.password}
                error={errors["password"]}
              />
              <button>Submit</button>
            </form>
    
            <button onClick={this.handleFacebook}>Login using Facebook </button>
            <button onClick={this.handleGoogle}>Login using Google </button>
          </React.Fragment>
        );
      }
    }
    
    export default LoginPage;

handleFacebook 和 handleGoogle 都不行。

我什至在我的frontend 中使用了proxy

我什至设置了这个:

app.options("/auth/google", (req, res, next) => {
    res.header('Access-Control-Allow-Origin', '*');
    res.header('Access-Control-Allow-Methods', 'GET,PUT,POST,DELETE,OPTIONS');
    res.header('Access-Control-Allow-Headers', 'Content-Type');        
    res.sendStatus(200);
});

我一直在搜索许多示例和代码,但没有任何帮助。

【问题讨论】:

    标签: node.js reactjs express axios cors


    【解决方案1】:

    问题是我不应该通过axios 获得/auth/google,而是应该通过a 标记将用户重定向到/auth/google 的后端,例如在/auth/google/callback/ 中设置redirectURLfrontendlocalhost

    这根本不是CORS 的问题。那是谷歌的问题,无法识别下一步该做什么,callback 永远不会被调用!

    【讨论】:

      猜你喜欢
      • 2021-06-21
      • 2011-01-08
      • 2023-01-02
      • 2020-10-04
      • 2020-08-09
      • 2017-07-06
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多