Home > Net >  Node JS session not work with Vue JS front
Node JS session not work with Vue JS front

Time:01-13


I am writing a Node JS backend application and Vue JS front, in the API I need session for keep authenticate the users

I use this components on backend server:

  • express (4.18.2)
  • express-session (1.17.3)
  • connect-mongo (3.3.8)
  • MongoDB 4.4.4

This is the boot code:

// import libs ---

import config from 'config'
import bodyParser from 'body-parser'
import { v4 as uuidv4 } from 'uuid'
import routes from './routes' // custom folder

import express from 'express'
import session from 'express-session'
import MongoStore from 'connect-mongo'

// set costant ---

const app = express()

const secret = config.get('secret')

// body parser ---

app.use(bodyParser.json())

// setup session ---

app.use(session({
    genid: function (req) { return uuidv4() }, // random id
    secret,
    store: MongoStore.create({ // connect to MongoDB fon Session storage
        mongoUrl: db.extendedURL,
        dbName: db.name,
        // autoRemove: 'native',
        // autoRemoveInterval: 10, // in minutes
        ttl: 7 * 24 * 3600 // in seconds
    }),
    cookie: { // cookies manage
        path: '/',
        maxAge: 6000000,
        httpOnly: false,
        secure: false,
        sameSite: false
    },
    stringify: false,
    saveUninitialized: true,
    resave: false,
    rolling: false,
    unset: 'destroy'
}))

// set server port (now run at localhost:5000) ---

app.set('port', 5000)

// set route ---

app.use('/', routes)

In ./route folder there are index.js imports perfectly

Here it is:

// import libs ---

import express from 'express'

const router = express.Router()

// routes ---

router.post('/login', function (req, res) {
    const { body, session } = req

    try {
        session.user = body.user

        console.log('user', session.user)

        req.session.save(function (err) {
            if (err) return res.status(400).json({ message: err })

            return res.status(200).json({ message: 'You have successfully authenticated' })
        })
    } catch (err) {
        return res.status(400).json({ message: err })
    }
})

router.get('/test', function (req, res) {
    const { session } = req

    try {
        console.log('session', session)

        return res.status(200).json(session)
    } catch (err) {
        return res.status(400).json({ message: err })
    }
})

export default router

When I try to call localhost:5000/login (post) I get all just fine, but when I call localhost:5000/test (get) I get a new session on the response and on MongoDB, it also happens whit multiple call on localhost:5000/test

Why express-session generate new session on every call? I really don't know, I spend few days in there and now i don't know how to do


EDIT (12/Jan/2023)

I managet to get it to work using this very simple CORS configuration on NodeJS server boot code:

app.use(cors({
    origin: 'http://localhost:8080',
    credentials: true
}))

and the header withCredentials: true on every simple http call from front

But this work only from localhost:8080
How can I do for call the Node JS server from other location without specify every IP addres?

Thank you

CodePudding user response:

To allow every origin you can do

app.use(cors({
    origin: '*',
    credentials: true
}))

or

app.use(cors({
    credentials: true,
    origin: true
})

Source : Why doesn't adding CORS headers to an OPTIONS route allow browsers to access my API?

  • Related