【问题标题】:How to work with Express-session Cookies for authentication with front-end and back-end separated如何使用 Express-session Cookie 进行前端和后端分离的身份验证
【发布时间】: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


    【解决方案1】:

    这正是 webpack devServer 的 proxy 的用途。如果您在 React 应用程序中使用 webpack,请在 webpack 配置中添加如下内容:

      devServer: {
        proxy: {
          '/api': 'http://localhost:5000',
        },
      },
    

    在开发过程中,您对localhost:3000 的所有请求都将带有cookies 标头,并将被重定向到您的本地节点服务器。

    自 2.0 版起,Parcel 也有开发 proxy server

    【讨论】:

      猜你喜欢
      • 2018-10-15
      • 2021-01-19
      • 2019-03-21
      • 1970-01-01
      • 2018-10-21
      • 2020-05-11
      • 2019-07-06
      • 2014-07-16
      • 2021-07-13
      相关资源
      最近更新 更多