Express cors 不允许凭据 [英] Express cors not allowing credentials
问题描述
我有一个使用 react
的前端设置和一个使用 express 和 mongodb
制作的后端,我有一个组件需要发出一个获取请求,其中包括应该已经设置好了.所有路线都适用于邮递员,但我无法使用 fetch 功能重新创建功能.快递服务器:
I have a frontend setup with react
and a back-end made with express and mongodb
, I have a component which needs to make a fetch request including the credentials with should be already set. All of the routes work on postman but I'm not able to recreate the functionality with the fetch function.
Express server:
...
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 功能.
As I said prior everything works on postman but not with the fetch function.
推荐答案
如错误所说:
响应中Access-Control-Allow-Origin"标头的值当请求的凭证模式为'包括'.
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'
标头设置为 '*'
.
When you do this server.use(cors())
, all of the requests are allowed by default and because of which, the 'Access-Control-Allow-Origin'
header is set to '*'
.
因此,您可能需要指定 corsOptions
来解决此问题.
So, you might want to specify the corsOptions
to get around this issue.
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));
这篇关于Express cors 不允许凭据的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!