Express cors 不允许凭据

Leo*_*ici 4 fetch express reactjs passport.js

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

...
    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"));
...
Run Code Online (Sandbox Code Playgroud)

用户路线:

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: "/"
  });
});
Run Code Online (Sandbox Code Playgroud)

前端:

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

      console.log(data);

    }

    fetchData();
  }, []);
Run Code Online (Sandbox Code Playgroud)

使用此代码我收到此错误

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'.
Run Code Online (Sandbox Code Playgroud)

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

Ana*_*via 7

正如错误所说:

当请求的凭据模式为“include”时,响应中“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));
Run Code Online (Sandbox Code Playgroud)