ExpressJS客户端会话不保存会话 [英] ExpressJS client-sessions don't save session

查看:96
本文介绍了ExpressJS客户端会话不保存会话的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想在我的Express后端使用客户端会话模块。所以我已经安装了模块,并将其设置为使用Express,如下所示:

I want to use client-sessions module with my Express backend. So I've installed the module and set it up to work with Express like this:

var sessions      = require('client-sessions');
app.use(sessions({
    cookieName: Constants.CLIENT_SESSION_NAME, // pi_client_session
    secret: Constants.CLIENT_SESSION_SECRET, // some long string here
    duration: Constants.CLIENT_SESSION_LIFETIME // 24 * 60 * 60 * 1000;
}));

但是,出于某种原因,每次请求都是空的。以下是示例:

But, for some reason, it's empty on every request. Here's the example:

router.get('/auth', function(req, res, next) {
    console.log("CLIENT SESSION BEFORE: " + JSON.stringify(req[Constants.CLIENT_SESSION_NAME]));
    req[Constants.CLIENT_SESSION_NAME].test = "saved";
    console.log("CLIENT SESSION AFTER: " + JSON.stringify(req[Constants.CLIENT_SESSION_NAME]));
    return res.json({ sessionSaved: true});
}

以下是我每次获得的输出:

And here is the output I get everytime:

CLIENT SESSION BEFORE: {}
CLIENT SESSION AFTER: {"test":"saved"}

我试过Google Chrome,Opera。同样的结果。

I've tried from Google Chrome, Opera. The same result.

我的设置是这样的:从localhost:3000到localhost:3001的ReactJS应用代理这是我的快递后端。
我已经尝试过直接请求与Postman一起表达,并且它正常保存了会话。所以问题肯定是代理从快速反应到快递和返回。
我的package.json FIL反应方面的e如下(我没有包含依赖项):

My setup is like this: ReactJS app proxies from localhost:3000 to localhost:3001 which is my express backend. I've tried direct requests to express with Postman, and it saved the session normally. So the problem is definitely in Proxying from react to express and back. My package.json file on react's side is as follows (I didn't include dependencies):

"scripts": {
    "build-css": "node-sass-chokidar src/ -o src/",
    "watch-css": "npm run build-css && node-sass-chokidar src/ -o src/ --watch --recursive",
    "start-js": "react-scripts start",
    "start": "npm-run-all -p watch-css start-js",
    "build": "npm run build-css && react-scripts build",
    "eject": "react-scripts eject"
  },
  "proxy": "http://localhost:3001"

所以问题是,如何使用这样的代理获得客户会话?

So the question is, how can I get client sessions using proxy like this?

推荐答案

因为您的React应用程序运行的源不同于您的后端,所以您需要明确告诉 fetch 传递凭据(喜欢cookies)每个请求:

Because your React app is running on a different origin than your backend, you need to explicitly tell fetch to pass credentials (like cookies) with each request:

fetch('http://your-backend', {
  credentials: 'include'  
}).then(...)

这篇关于ExpressJS客户端会话不保存会话的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆