Я работаю над веб-приложением Mern Stack (реагировать, узел, экспресс и mongodb).Я установил экспресс-сессию на node.js.однако в браузере я не вижу cookie-файл connect.sid.Кроме того, кажется, что сеанс не сохраняется между запросами в узле.
Сначала я думал, что это проблема 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 и файл cookie, сохраненный в браузере.
Фактический результат: сеанс не сохраняетсяи cookie не сохраняется.