gpt4 book ai didi

reactjs - Express cors 不允许凭据

转载 作者:行者123 更新时间:2023-12-02 19:59:01 25 4
gpt4 key购买 nike

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

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

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

最佳答案

如错误所述:

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

当您执行此操作时 server.use(cors()),默认情况下允许所有请求,因此,'Access-Control-Allow-Origin' header 设置为 '*'

因此,您可能需要指定 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));

关于reactjs - Express cors 不允许凭据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56328049/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com