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.
The Session Storage basically consists of 4 main methods. setItem(key, value): This method is used to set the value into the Session Storage based on the key. getItem(key): This method is used to get the value that is stored into the Session Storage. It takes a key and returns the value.
Try something like: app. use( session( { secret: 'keyboard cat', cookie: { maxAge: 60000 }, rolling: true, resave: true, saveUninitialized: false } ) );
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.
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.
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')
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With