如何处理客户端的Express会话cookie?

发布于 2025-01-18 14:44:14 字数 1537 浏览 3 评论 0原文

我正在尝试使用 Express 创建一个 API,我将使用 React 前端访问它。我很难弄清楚如何使用快速会话处理身份验证。

我使用的中间件如下:

var corsOptions = {
  credentials: true,
  origin: 'http://localhost:3000'
}
app.use(cors(corsOptions));

app.use(session({
    secret: 'dfgdfbgbdfgd',
    saveUninitialized: false,
    resave: false,
    cookie: {
        secure: false
    }
}));

这是登录路由(local_auth 中间件只是检查凭据是否正确):

AccountRouter.post('/login', local_auth, (req, res) => {
    req.session.user_id = req.user._id;
    return res.status(200).send('Connected');
});

登录后,我尝试从 React 访问以下路由以检查会话是否可操作:

AccountRouter.get('/authcheck', (req, res) => {
    let sess = req.session.user_id;
    console.log(sess);
    if (sess) return res.status(200);
    else return res.status(404).send('pffff');
 });

req.会话未定义。 前端代码只是对上述url的简单axios请求。我不知道是否必须将 cookie 保存到 localStorage 并为每个请求发送每个 cookie。

这是对 authcheck 路由的请求:

axios.get('http://localhost:5000/api/accounts/authcheck', {withCredentials: true})
    .then((response) => {
        console.log(response);
    })
    .catch(() => {
        console.log('waaah va te connecter');
    });

以及登录请求:

const data = {
        'email': e.target.email.value,
        'password': e.target.password.value
    };

    axios.post('http://localhost:5000/api/accounts/login', data)
    .then((response) => {
        const sessionID = response.data;
        console.log(sessionID);
    });

I'm trying to create an API with express that I will access using a React front end. I'm having a hard time figuring out how to handle authentication using express-session.

I used the middleware like follows:

var corsOptions = {
  credentials: true,
  origin: 'http://localhost:3000'
}
app.use(cors(corsOptions));

app.use(session({
    secret: 'dfgdfbgbdfgd',
    saveUninitialized: false,
    resave: false,
    cookie: {
        secure: false
    }
}));

Here is the Log in route (the local_auth middleware is just checking if the credentials are correct):

AccountRouter.post('/login', local_auth, (req, res) => {
    req.session.user_id = req.user._id;
    return res.status(200).send('Connected');
});

After loging in, I try to access the following route from React to check if the session is operational:

AccountRouter.get('/authcheck', (req, res) => {
    let sess = req.session.user_id;
    console.log(sess);
    if (sess) return res.status(200);
    else return res.status(404).send('pffff');
 });

req.session is undefined.
The front end code is just a simple axios request to the above url. I have no idea if I have to save the cookie to localStorage and send each for each request.

Here is the request to the authcheck route:

axios.get('http://localhost:5000/api/accounts/authcheck', {withCredentials: true})
    .then((response) => {
        console.log(response);
    })
    .catch(() => {
        console.log('waaah va te connecter');
    });

And the login request:

const data = {
        'email': e.target.email.value,
        'password': e.target.password.value
    };

    axios.post('http://localhost:5000/api/accounts/login', data)
    .then((response) => {
        const sessionID = response.data;
        console.log(sessionID);
    });

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

奶气 2025-01-25 14:44:14

req.session不确定。

如果req.sessionundefined,那么您显然正在尝试在此中间件代码之前定义的路由中使用会话:

app.use(session({
    secret: 'dfgdfbgbdfgd',
    saveUninitialized: false,
    resave: false,
    cookie: {
        secure: false
    }
}));

有机会运行。当req.session 时,这意味着会话代码尚未运行。即使您遇到了导致先前会话丢失的cookie问题,如果会话中间件已经运行,您仍然会有一个新的空req.session

因此,由于您没有显示所有路线的总体顺序,因此我们无法提供特定的修复程序,但是看来:

AccountRouter.get('/authcheck, ...)

在您的会话中间件之前运行,这对于任何取决于会话的路线都是一个问题。

req.session is undefined.

If req.session is undefined, then you are apparently trying to use the session in a route that is defined BEFORE this middleware code:

app.use(session({
    secret: 'dfgdfbgbdfgd',
    saveUninitialized: false,
    resave: false,
    cookie: {
        secure: false
    }
}));

has had a chance to run. When req.session is undefined, that means the session code has not yet run. Even if you had a cookie issue that causes a prior session to get lost, you would still have a new empty req.session if the session middleware had already run.

So, since you don't show the overall order of all your routes, we can't offer a specific fix, but it appears that this:

AccountRouter.get('/authcheck, ...)

is running before your session middleware which is a problem for any route that depends upon the session.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文