【发布时间】:2019-10-20 06:15:15
【问题描述】:
我正在开发一个 mern stack(react、node、express 和 mongodb)网络应用程序。 我已经在 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 文件。
实际结果:Session不持久,cookie不存储。
【问题讨论】:
-
更新:我还没有解决这个问题,我只是注意到我正在使用邮递员而不是浏览器获取会话 cookie。
-
你有解决办法吗...我被困在这里了?
标签: javascript node.js reactjs express express-session