Express Cors不允许凭证

时间:2019-05-27 14:31:47

标签: reactjs express fetch 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"));
...

用户路线:

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'.

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

2 个答案:

答案 0 :(得分:1)

错误提示:

  

响应中“ 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));

答案 1 :(得分:-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)