Issue saving cookies while using express-sessions in MERN project

  Kiến thức lập trình

I am having a hard time saving the cookies on the client side of a MERN project. This is how the entry point of my server looks like:

const express = require('express');
const app = express();
const mongoose = require('mongoose');

const session = require('express-session');
const cors = require('cors');
const MongoDBSession = require('connect-mongodb-session')(session);

let PORT = process.env.NODE_PORT;

mongoose.connect(process.env.DB_URL, {
    useUnifiedTopology: true,
    useNewUrlParser: true,
    useFindAndModify: false,
    useCreateIndex: true
}).then(
    () => {
           console.log('Database is connected');
    },
    err => {
        console.log('Could not connect to the database. ' + err)
    });

const store = new MongoDBSession({
    uri: process.env.DB_URL,
    collection: 'sessions'
});

app.use(session({
    secret: process.env.SESSION_SECRET,
    resave: false,
    saveUninitialized: false,
    cookie: {
        domain: '.frontend-domain.me',
        sameSite: 'none',
        secure: true,
        httpOnly: true,
        maxAge: 24 * 60 * 60 * 1000
    },
    store: store
}));

app.use(cors({
    origin: 'https://frontend-domain.me',
    methods: ['GET', 'PUT', 'POST', 'DELETE'],
    allowedHeaders: ['X-PINGOTHER', 'Content-Type'],
    credentials: true,
    maxAge: 86400
}));

// Some routes

app.get('*', (req, res) => {
    res.sendStatus(404);
});
const server = app.listen(PORT, function () {
    console.log(`Server Connected on port #${PORT}. Restart Occured at ${new Date()}`);
    process.send('ready');
});

and my front end request that is used to set the session variable is like the following:

 axios.post('/route/to/my/server', {
    email: this.state.email,
    password: this.state.password

}, { withCredentials: true })
    .then(res => {
        // do something
    })
    .catch(err => {
        // handle
    });

to handle this request i have a file at my server that is:

router.post('/my/server', (req, res) => {
    // if the user is matched then:

    console.log("Logged in successfully");
    req.session.user = user;
    req.session.loggedin = true;
    req.session.save(function(err) {
        res.send({ 
            loggedin: true,
        });
    });
});

I have tried changing the cors settings, tries changing the cookies settings on the chrome, still no good response. After the response my cookies are not set: See image
and when i try to access the session variables in the next request, the session variables are not present there. Although session variables are stored in the Database.

Theme wordpress giá rẻ Theme wordpress giá rẻ Thiết kế website

LEAVE A COMMENT