【发布时间】:2021-10-23 11:19:30
【问题描述】:
设置
后端:Express.js、express-session、connect-mongo、cors、在 Heroku(免费版)的 Node.js 主机中工作的模块,以及将数据存储到 MongoDB Atlas(基于云Mongo解决方案)
前端:React.js、axios,在 Godaddy 共享 linux 主机上工作。
我使用 Heroku 免费域 (https://app-name.herokuapp.com),并为 Godaddy 购买了一个域。
另外,对于免费的 HTTPS 证书,我使用 Cloudflare(免费版)。
问题
前端和后端之间的通信运行良好。发送和接收数据。但是,在我需要实现的登录系统中,数据被发送,正确通过数据库检查,之后,我将会话保存到数据库。它运行良好,直到 COOKIE 设置部分,当我没有收到前端域中的会话 COOKIE 时。
代码
app.js
// In my app.js, the entry point for backend
// ---> This line is just after module importing.
dotenv.config();
const storage = new store({
mongoUrl: ""+process.env.MONGODB_URI, collectionName: "sessions", ttl: 100, autoRemove: "native"
});
app.disable("X-Powered-By");
app.use(cors({origin: "https://my.godaddy.subdomain", credentials: true, methods: "GET, POST, PUT, DELETE"}));
app.use(function(req, res, next) {
res.header("Access-Control-Allow-Credentials", true);
res.header("Access-Control-Allow-Origin", "https://my.godaddy.subdomain");
res.header("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept, Authorization, X-HTTP-Method-Override");
res.header("Access-Control-Allow-Methods", "GET,POST,DELETE,PUT,OPTIONS");
next();
});
// "my.godaddy.subdomain" is the SUBDOMAIN where i have an Administrators' login page, so it is separated from public site "godaddy.subdomain" (ONLY FOR EXAMPLE PURPOSE)
app.use(express.json());
app.use(express.urlencoded({extended: false}));
mongo.connect(""+process.env.MONGODB_URI,
{
useNewUrlParser: true,
useUnifiedTopology: true,
dbName: "Test_DB"
}
).then(() => console.log("Connected to MongoDB!"))
.catch((err) => console.log("Error connecting to MongoDB: "+err));
app.use(session({
name: "admin_session",
secret: ""+process.env.SERVER_SECRET,
resave: true,
rolling: false,
saveUninitialized: false,
unset: "destroy",
cookie: {
sameSite: "none", // I tried changing this a thousand times, no result...
secure: true, // The maximum i could was set a session sucessfully IN THE HEROKU
httpOnly: true, // BACKEND (no cross-domain), but that would be useless...
maxAge: 8600000
},
store: storage
}));
// ---> After this line, the routing code, all working fine.
admin_routing.js
// The Admin route, called admin_routing.js, used in app.js
router.route("/admin/login").post(async (req, res, next) =>
{
const {username, password} = req.body;
const admin = await Admin.find({user_login: username}).then((doc) => doc.pop());
if(admin.user_login === username)
{
await bcrypt.compare(password, admin.user_pass).then((same) =>
{
if(same)
{
req.session.adminID = admin._id;
req.session.save((err) => console.log(err)); // here i save the session
console.log(req.body, req.session); // it is sucessfully saved but
res.send({error: "Sucess!"}); // NO COOKIE IS SENT...
}
else
{
res.send({error: "Check your credentials and try again."});
}
});
}
else
{
res.send({error: "No administrators found."});
}
});
前端请求(登录组件)
// The part of my frontend where i post login data, in a React.js Component
await axios.post("https://my-app.herokuapp.com/admin/login",
{username: Inputs[0].value, password: Inputs[1].value}, {withCredentials: true, method: "POST",
headers: {'Access-Control-Allow-Origin': 'https://my-app.herokuapp.com'}})
.then((res) =>
{
document.getElementById("err-bc").innerText = ""+res.data.error; // Design purpose
document.getElementById("err-bc").style.visibility = "visible";
console.log(res.data);
}).catch((err) =>
{
document.getElementById("err-bc").innerText = ""+res.data.error; // Design purpose
document.getElementById("err-bc").style.visibility = "visible";
});
修复后应该如何工作
它必须保存会话,将 cookie 发送回我的子域中的前端,并且当登录的 ADMIN 用户访问公共页面时,它仍必须保留 cookie 以进行身份验证。 因此 adm.mydomain.com 接收到身份验证 cookie,并在用户访问 mydomain.com 和 www.mydomain.com(公共页面)时保留它。
希望有人给出答案,现在我已经尝试解决了两天。
谢谢。
【问题讨论】:
标签: node.js express cookies cross-domain express-session