Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

671
Visualizações
Storing variable in session with ejs and node js

Im trying to think of a solution to the following issue: I have a variable that needs to be separate for every unique visitor on the page. Its just simple list that is filled when a visitor clicks on some items on the page. It would be empty for each unique visit. Currently Im keeping that in the backend, it is pretty bad solution as everyone currently using the app is adding to the same list

The backend code:

thelist=[]

app.get("/show/:id", function (req, res) {
 var id = req.params.id;
 thelist.push(id)
 console.log(thelist);
 res.redirect('/')
});

app.get("/run", function(req, res) {
 res.render("data", {data: thelist})
 thelist = []
});

The main point is that list thelist is then passed to a python script which is also connected via node.js into the app. Therefore i need that variable to stay in the backend. Also I was thinking of keeping it simple, so I don't want to force users to create account to use the app, so some sort of cookies/cache/any other form of session storage is what im looking for.

over 4 years ago · Santiago Trujillo
3 Respostas
Responde à pergunta

0

You can create a session map(like hashmaps). I have integrated the same in one of my projects and it is working flawlessly. Below is the code for it and how you can access it:

hashmap.js

var hashmapSession = {};

exports.auth = auth = {
  set : function(key, value){
    hashmapSession[key] = value;
  },
  get : function(key){
    return hashmapSession[key];
  },
  delete : function(key){
    delete hashmapSession[key];
  },
  all : function(){
    return hashmapSession;
  }
};

app.js

var hashmap = require('./hashmap');
var testObj = { id : 1, name : "john doe" };

hashmap.auth.set('test', testObj);
hashmap.auth.get('test');
hashmap.auth.all();
hashmap.auth.delete('test');

You can use this approach as a session storage for your node application. Keep in mind that this storage will only be persistent for the current session only.

over 4 years ago · Santiago Trujillo Relatório

0

The best solution here would be express session (https://github.com/expressjs/session)

As I see your code I can figure out you are using express. And if you are using express that is enough for below code.

Here is the easiest way with minimal code to achieve what you are looking for:

Example:

app.set('oneSetting', 'one');
console.log(app.settings.oneSetting);

OR

   app.set('port', 3000);

   app.get('port'); //3000

You can access the same variables in the req object too, example:

req.app.get('port')
over 4 years ago · Santiago Trujillo Relatório

0

Why don't you use express-session.

You can use it like the following :

App.js

var app = express();
app.use(session({
  secret: 'keyboard cat',
  resave: false,
  saveUninitialized: true,
  cookie: { secure: true }
}))

Controller.js

//Sets the id in the session object.
app.get('/show/:id', function (request, response, next) {
  request.session.id = id;
})

//Retrieve the id from the session object.
app.get('/showMyId',function(request,response,next)){
  response.send(request.session.id;);
})

This way you do not have to manage the global list and all your ids would be present inside their respective session object.

This approach uses a cookie session , there are also alternative strategies available for storing your session object like a proper storage server.

over 4 years ago · Santiago Trujillo Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda