快速会话不会持续,也不会向浏览器发送Cookie

时间:2019-06-04 17:16:34

标签: javascript node.js reactjs express express-session

我正在使用Mern堆栈(反应,节点,快速和mongodb)Web应用程序。 我已经在node.js上安装了express-session。但是,我在浏览器中看不到connect.sid cookie。而且,会话似乎在节点中的请求之间不会持久。

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

//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框架上的持久会话ID和存储在浏览器中的cookie文件。

实际结果:会话不持久并且不存储cookie。

1 个答案:

答案 0 :(得分:0)

修复更新: 问题是未在获取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设置中,不能将通配符('*')用作“访问控制允许来源”。相反,它需要原始地址,在我的情况下是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是不够的。 需要手动关闭服务器才能进行更改。对我来说,这是路径上的真正障碍。