express-session 不会持续存在,也不会向浏览器发送 cookie

express-session won't persist and won't send a cookie to the browser

我正在开发 mern 堆栈(反应、节点、快递和 mongodb)网络应用程序。 我已经在 node.js 上安装了 express-session。但是,我在浏览器中没有看到 connect.sid cookie。此外,session 似乎不会在节点中的请求之间持续存在。

我最初认为这是一个 cors 问题(可能仍然是这种情况)所以我尝试对 CORS headers 进行一些调整,但没有任何运气。

//this is the main app.js file in node.js

var session = require('express-session')

app.use((req, res, next) => {
    res.header('Access-control-Allow-Origin', '*');
    res.header(
        "Access-Control-Allow-Headers",
        "Origin, X-Requested-With, Content-Type, Accept, Authorization"
    );
    res.header('Access-Control-Allow-Credentials', true);
    if (req.method === 'OPTIONS') {
        res.header('Access-Control-Allow-Methods', 'PUT, POST, PATCH, DELETE, GET');
        return res.status(200).json({});
    }
    next();
});

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

//this is the index.js route file in node.js

router.get('/check_if_session_exists_when_refreshing', async (req, res, next) => {
  try {
    res.json(req.session)
  }
  catch (err) {
    console.log(err);
  }
});

router.post('/login', function (req, res, next) {
  UserModel.findOne({ username: req.body.username }).then((data) => {
    bcrypt.compare(req.body.password.toString(), data.password.toString()).then((resp, err) => {
      if (resp) {
        req.session.user = {
          username: req.body.username,
          password: req.body.password
        }
        res.json([data])
      }
      else console.log(err)
    })
  });
});
// this is the React-Redux login action on the client side
import { FETCH_USER } from './types';

export const fetchUser = (userData) => dispatch => {
    fetch("http://localhost:3000/login", {
        method: 'POST',
        headers: { 'content-type': 'application/json' },
        body: JSON.stringify(userData)
    }).then(response => response.json())
        .then(user =>
            dispatch({
                type: FETCH_USER,
                payload: user
            })
        );
};

预期结果:express 框架上的持久性 session id 和浏览器中存储的 cookie 文件。

实际结果:Session 不持久且不存储 cookie。

修复更新: 问题是凭证初始化选项没有在获取时设置 API.

正确的代码应该这样写:

// this is the React-Redux login action on the client side

export const fetchUser = (userData) => dispatch => {
fetch("http://localhost:3000/login", {
    method: 'POST',
    headers: { 'content-type': 'application/json' },
    credentials: "include",
    body: JSON.stringify(userData)
}).then(response => response.json())
    .then(user =>
        dispatch({
            type: FETCH_USER,
            payload: user
        })
    );
};

此外,在 CORS 设置中,通配符 ('*') 不能用作 'Access-Control-Allow-Origin'。相反,它需要原始地址,在我的例子中是 http://localhost:3001.

//this is the main app.js file in node.js

app.use((req, res, next) => {
res.header('Access-control-Allow-Origin', 'http://localhost:3001');
res.header(
    "Access-Control-Allow-Headers",
    "Origin, X-Requested-With, Content-Type, Accept, Authorization"
);
res.header('Access-Control-Allow-Credentials', true);
if (req.method === 'OPTIONS') {
    res.header('Access-Control-Allow-Methods', 'PUT, POST, PATCH, DELETE, GET');
    return res.status(200).json({});
}
next();
});

回想起来,我很早就想到了这一点。但我不知道,在进行这些更改后重置 nodemon 是不够的。 需要手动关闭服务器才能进行更改。