niddddddfier
niddddddfier

Reputation: 517

Nuxt : How to get the session values from express

I tried to get a value from express session (req.session.userid) in Nuxt by this.$session.userid, but I couldn't get the value in console.log.

It just showed "Cannot read properties of undefined (reading 'userid')"

If I get the value of this.$session then it just showed 'undefined'

If I want to get the value through the session normally, then how I need to call the value? Or can't I get the value by the session?

/nuxt.config.js

export default{
  components: true,
  buildModules: [
    '@nuxtjs/dotenv'
  ],
  modules: [
    '@nuxtjs/dotenv', 'cookie-universal-nuxt',
  ],
  router: {
    middleware: ['auth']
  },
  serverMiddleware: [
    '~/server/app.js',
  ],
}

/server/app.js

const express = require('express')
const app = express()
const session = require('express-session')
const cors = require('cors')

app.use(cors())
//body-parser added
app.use(express.json())
//session added
app.use(session({
  secret: 'secret key',
  resave: false,
  saveUninitialized: true
 }))

...

app.use('/login_router', require('./routes/login_router'))

/server/routes/login_router.js

const express = require('express');
const router = express.Router();

const path = require('path');

router.get('/testGetUserid', function(req, res){
  req.session.userid = '10101'
  console.log('req.session.userid>>>>>>', req.session.userid)
  res.redirect('/login')
});

/pages/login.vue

<template>
    <button @click="submitTest">Get the userid</button>
</template>

<script>
export default {
    methods:{
        submitTest(){
            console.log('this.$session.userid>>>', this.$session.userid) // I want to see this value as 10101
        }
    }
}
</script>

Upvotes: 1

Views: 1931

Answers (1)

kusiaga
kusiaga

Reputation: 695

I assume that you are using SPA mode.

So you can use API to get that userId.

router.get('/testGetUserid', function(req, res){
  req.session.userid = '10101'
  
  res.json({ userId: req.session.userid })
});

If you want to get userId in another endpoint, I think you can do like this. I haven't tried it but I believe the session is accessbile anywhere in your backend code once you have set it in /testGetUserid.

Example you have /user route

router.get('/user', function(req, res){
  const userId = req.session.userid
  
  // do something
  
  res.json(someJSON)
});

in Nuxt

<script>
export default {
    methods:{
        submitTest(){
          axios.get('/testGetUserid', { withCredentials: true }).then(res => {
            // here you can get the userId, you can store it in variable or vuex
            conosle.log(res.data.userId)
          })
        }
    }
}
</script>

Upvotes: 1

Related Questions