【问题标题】:Express cors not allowing credentialsExpress cors 不允许凭据
【发布时间】:2022-01-14 19:12:18
【问题描述】:

我有一个使用react 的前端设置和一个使用express and mongodb 的后端,我有一个组件需要发出获取请求,包括应该已经设置的凭据。所有路线都适用于邮递员,但我无法使用 fetch 功能重新创建功能。 快递服务器:

...
    server.use(helmet());
    server.use(compression());
    server.use(cors({
      credentials: true,
    }));

    if (process.env.NODE_ENV !== "production") {
      server.use(logger("dev"));
    }
    server.use(express.json());
    server.use(express.urlencoded({ extended: false }));

    server.use(cookieParser());

    server.use(
      session({
        secret: process.env.COOKIE_SECRET,
        resave: true,
        saveUninitialized: false,
        store: new MongoStore({ mongooseConnection: mongoose.connection })
      })
    );

    server.use(auth.initialize);
    server.use(auth.session);
    server.use(auth.setUser);

    //API ROUTES
    server.use("/user", require("./api/routes/user"));
    server.use("/pitch", require("./api/routes/pitch"));
    server.use("/match", require("./api/routes/matchmaking"));
...

用户路线:

router.post("/login", passport.authenticate("local"), (req, res, next) => {
  return res.status(200).json({
    message: "User logged in correctly",
    redirect: "/"
  });
});

router.get("/checklogin", (req, res, next) => {
  if (req.user) return next();
  else
    return res.status(401).json({
      error: "User not authenticated"
    });
},
 (req, res, next) => {
  return res.status(200).json({
    message: "User logged in correctly",
    redirect: "/"
  });
});

前端:

  useEffect(() => {
    async function fetchData() {
      const response = await fetch("http://localhost:8000/user/checklogin", {
        credentials: 'include'
      });
      const data = await response.json();

      console.log(data);

    }

    fetchData();
  }, []);

使用此代码出现此错误

Access to fetch at 'http://localhost:8000/user/checklogin' from origin 'http://localhost:3000' has been blocked by CORS policy: The value of the 'Access-Control-Allow-Origin' header in the response must not be the wildcard '*' when the request's credentials mode is 'include'.

正如我之前所说,一切都适用于邮递员,但不适用于 fetch 功能。

【问题讨论】:

    标签: reactjs express fetch passport.js


    【解决方案1】:

    你可以这样做 快递中

    app.use(cors({credentials: true, origin: 'http://localhost:3000'}));
    app.use(function(req, res, next) {
        res.header("Access-Control-Allow-Origin", 'http://localhost:3000');
        res.header("Access-Control-Allow-Credentials", true);
        res.header('Access-Control-Allow-Methods', 'GET,PUT,POST,DELETE,OPTIONS');
        res.header("Access-Control-Allow-Headers", 'Origin,X-Requested-With,Content-Type,Accept,content-type,application/json');
        next();
    });
    

    在路由器中

    router.all('*', cors());
    

    发送响应时做

     res.header("Access-Control-Allow-Origin", 'http://localhost:3000');
     res.json(someJson)
    

    【讨论】:

      【解决方案2】:

      正如错误所说:

      响应中“Access-Control-Allow-Origin”标头的值 当请求的凭证模式为 '包括'。

      当您这样做server.use(cors()) 时,默认情况下允许所有请求,因此'Access-Control-Allow-Origin' 标头设置为'*'。

      因此,您可能需要指定 corsOptions 来解决此问题。

      var whitelist = ['http://localhost:3000', /** other domains if any */ ]
      var corsOptions = {
        credentials: true,
        origin: function(origin, callback) {
          if (whitelist.indexOf(origin) !== -1) {
            callback(null, true)
          } else {
            callback(new Error('Not allowed by CORS'))
          }
        }
      }
      
      server.use(cors(corsOptions));
      

      【讨论】:

      • 谢谢你,我照你说的做了,但我得到(未经授权)即使用户登录...
      • 嗯,我想 LocalStrategy 没有完全设置好。您是否正确安装了serializeUser 和deserializeUser ?
      • 我也没有看到passport.init() 和passport.session()。您是否遵循了here 中的所有步骤
      • 我找到了解决方案,它涉及到无法保存会话 cookie 的 fetch 功能,这就是它不起作用但您的解决方案仍然有帮助的原因
      • 我很高兴它有帮助!
      猜你喜欢
      • 2018-08-17
      • 1970-01-01
      • 2020-05-25
      • 1970-01-01
      • 2017-12-28
      • 1970-01-01
      • 2015-01-15
      • 2020-07-02
      相关资源
      最近更新 更多