【发布时间】:2021-09-14 15:13:09
【问题描述】:
我试图弄清楚会话如何用于身份验证。我有一个在端口 5000 上运行的快速服务器,redis 中间件在对后端服务器的每个响应上创建 cookie。我还有一个在 3000 端口上运行的 React 应用程序来处理前端。问题是,如果有人访问“localhost:3000”,则不会创建 cookie,因为他们需要访问“localhost:5000”才能创建 cookie。
我能想到的唯一解决方案是每次都使用 useEffect() 向服务器发出请求以获取 cookie。我不确定这是否是正确的方法。
服务器.ts:
import express from "express";
import redis from "redis";
import session from "express-session";
import connectRedis from "connect-redis";
import cors from "cors";
declare module "express-session" {
interface Session {
username: string;
password: string;
email: string;
}
}
const RedisStore = connectRedis(session);
const redisClient = redis.createClient();
redisClient.on("error", function (err) {
console.log("Could not establish a connection with redis. " + err);
});
redisClient.on("connect", function () {
console.log("Connected to redis successfully");
});
const app = express();
const corsOptions = {
origin: "http://localhost:3000",
};
app.use(cors(corsOptions));
app.use(express.json());
app.use(express.urlencoded({ extended: true }));
app.use(
session({
name: "joshcookie",
store: new RedisStore({ client: redisClient, disableTouch: true }),
cookie: { maxAge: 1000 * 60 * 60 * 24, httpOnly: false, secure: false },
secret: "jklbflasjlkdbhfoub4ou",
saveUninitialized: true,
resave: false,
})
);
app.get("/", (req: express.Request, res: express.Response) => {
const session = req.session;
console.log(req.session.id);
if (session.username) {
res.send("user logged in");
} else {
res.send("user not logged in");
}
});
app.post("/register", (req, res) => {
console.log(req.body);
req.session.username = req.body.username;
res.end();
});
app.listen(5000, () => {
console.log("server listening on port 5000");
});
【问题讨论】:
标签: node.js express session cookies redis