my program looks as follows:
var globVar=[];
function1(usr){
//calculations with globVar
}
function2(usr){
//calculations with globVar
}
app.post('/', function(req, res) {
var formString = req.body.filter1;
globVar.push(formString);
usr= req.connection.user;
function1(usr);
function2(usr);
res.redirect('/');
});
req.connection.user comes from nodeSSPI module. I need to make this globVar user specific so it doesn't mixed up when users runs this app concurrently. Now it works well but only for single user :)
Thank you for your consideration on this matter.
I've been looking at what seems like the same problem and my solution was to simply use cookies, and set a variable within the cookies client-side.
In my case the problem was setting language choice permanently for each user and that was simplest.
This guide helps:
https://www.tutorialspoint.com/expressjs/expressjs_cookies.htm
Related
I have a proprietary math formula written in a javascript function that I need to make available for a website to use it without them actually having access to the code itself.
Is it possible?
The idea is to make the formula available online without people being able to read the code. I have no idea how to do it.
I read about private packages on npm, but it seems to restrict prople who can use and read the code. I need them to use it but not read it.
If the code is run on the client's machine in any way, it will be possible for any sufficient dedicated and persistent user to find it, eventually; all code that runs on a page can be found through the browser devtools.
The only way for true privacy for such a thing would be to not send the code that implements the formula to the client in the first place. Set up a server, if you don't already have one, and create a very simple API for it - one that takes the inputs for the formula as, say, a POST request, runs the formula that calculates the result on the server, and responds to the client with the result.
Use node.js to create an express server that listens for incoming requests and then send back the result to the client in the response
const express = require('express');
const app = express();
function proprietaryFormula(x, y) {
// the formula goes here
return x + y;
}
app.get('/formula', (req, res) => {
let x = req.query.x;
let y = req.query.y;
let result = proprietaryFormula(x, y);
res.send(result);
});
app.listen(3000, () => {
console.log('started listening on port 3000');
});
The website can call this API to access the formula's functionality, and the code for the formula is kept on the server and never exposed to the client-side.
I've been working on a server and a push notification daemon that will both run simultaneously and interact with the same database. The idea behind this is that if one goes down, the other will still function.
I normally use Swift but for this project I'm writing it in Node, using Mongoose as my database. I've created a helper class that I import in both my server.js file and my notifier.js file.
const Mongoose = require('mongoose');
const Device = require('./device'); // This is a Schema
var uri = 'mongodb://localhost/devices';
function Database() {
Mongoose.connect(uri, { useMongoClient: true }, function(err) {
console.log('connected: ' + err);
});
}
Database.prototype.findDevice = function(params, callback) {
Device.findOne(params, function(err, device) {
// etc...
});
};
module.exports = Database;
Then separately from both server.js and notifier.js I create objects and query the database:
const Database = require('./db');
const db = new Database();
db.findDevice(params, function(err, device) {
// Simplified, but I edit and save things back to the database via db
device.token = 'blah';
device.save();
});
Is this safe to do? When working with Swift (and Objective-C) I'm always concerned about making things thread safe. Is this a concern? Should I be worried about race conditions and modifying the same files at the same time?
Also, bonus question: How does Mongoose share a connection between files (or processes?). For example Mongoose.connection.readyState returns the same thing from different files.
The short answer is "safe enough."
The long answer has to do with understanding what sort of consistency guarantees your system needs, how you've configured MongoDB, and whether there's any sharding or replication going on.
For the latter, you'll want to read about atomicity and consistency and perhaps also peek at write concern.
A good way to answer these questions, even when you think you've figured it out, is to test scenarios: Hammer a duplicate of your system with fake data and events and see if what happen is OK or not.
I'm new to node.js and sessions, I'm trying to store some values in the node.js session, but everytime I reload the page and check the console.log the session haven't been saved. My code:
var session;
var org;
function checkSession(argument){
var sess = argument;
if(sess.org){
return null;
}
else{
return sess.org;
}
}
/* GET home page. */
router.get('/', function(req, res, next) {
session = req.session;
var sessionChecked = checkSession(session);
if(sessionChecked){
org = sessionChecked;
}
else{
org = req.query.org || 'Google';
session.org = org;
session.save();
}
So basically what I want is, when the user loads the page for the first time, he can type a organization, and when he does that, this organization is saved on the session, so when he reloads the page, the organization is already selected.
I know I must be doing something really wrong and/or bad codding, but I just can't figure this out.
Thank you!
It looks like calling session.save() isn't doing what you expect. Express won't write to the session unless the route is fully processed. You likely need to call res.end() at the end of your get function.
Take a look at https://github.com/expressjs/session#reqsession and try to understand each line of code in that example.
Good luck!
It turns out the problem was that my session was expiring in 20 seconds. Silly me.
So, I was told that passing around the request and or response variable in nodeJS is "bad practice". But this means that most of your code has to be in the server.js file, making it cluttered and kind of ugly.
How can you modularize your nodejs server, passing around req/res appropriately and be able to organize your code into separate files?
For example, I would like to split my socket routing, .get and .post into different files, but still be able to use the callback parameters like so:
app.io.route("disconnect", function(req,res) { <--- these params
db.query("UPDATE player_data SET online=0 WHERE id="+mysql.escape(req.session.user));
req.io.broadcast("event", {msg:req.session.username+" has logged out!"});
app.io.broadcast("reloadXY");
});
As of right now they're all in one file and I don't like that.
I think what the person meant by 'passing around' was something like this (in plain express):
app.get('/kittens', function(req, res) {
db.doAthing(req);
updateSomethingElse(res);
upvoteThisAnswer(res);
});
That is, passing around the two variables beyond the first function. This is bad because it becomes increasingly difficult to figure out where the call actually ends. One little res.end(500) in updateSomethingElse can cause the whole house of cards to come tumbling down.
It's perfectly ok (in fact, standard to the point of being the default in express) to declare that callback elsewhere (usually the /routes directory of your project.)
// app.js
var user = require('./routes/user')
, kittens = require('./routes/kittens');
// express stuff...
app.get('/settings', user.getSettings);
app.get('/fur', kittens.shed);
Then, in routes/user.js:
exports.getSettings = function(req, res) {
// Note how we're passing around properties of req/res, not the objects themselves.
db.getUserSettings(req.user.id).then(function(settings) {
res.render('settings', settings);
});
};
This video from TJ Holowaychuk (the guy who wrote Express and a ton of other Node infrastructure that we all use) helped me take Express modularization to the next level. Basically you can make individual apps in their own folders and consume them as middleware very easily. I have managed to extend this technique to socket.io with some tricks.
http://vimeo.com/56166857
You should not pass req and res to another modules but pass callbacks from another modules to route.
It should look like.
var someModule = require("./someModule")
app.get("/someAction", someModule.handleSomeAction) ;
If You want to have post and get in another modules You should pass reference to app (from express()) once to that module and operate on that.
For example :
var express = require("express") ;
var app = express();
var get_handler = require("./get_handler ")
var post_handler = require("./post_handler ")
get_handler.init(app);
post_handler.init(app);
and in post/get_handler :
var app;
exports.init = function( eApp){
app = eApp;
// operate on app
}
Is it possible to automate routing in Express, so I don't have to list out all the routes?
For example: going to URL '/users/first_example' should automatically use the "users.first_example" module.
app.get('/users/:name', function(req,res){
return eval('users.'+req.params.name); //failed attempt
});
There's got to be something I'm missing, and it would make my code look a lot more elegant.
Much appreciated.
var users = require('./users');//a module of route handler functions
app.get('/users/:name', function(req,res){
var handler = users[req.params.name];
if (typeof handler === 'function') {
return handler(req, res);
}
res.status(404).render('not_found');
});
You might want to check this earlier answer on stackoverflow - https://stackoverflow.com/a/6064205/821720
A little more code but abstracts routing to the next level and also gives you a cleaner main file.
I have been working on something like this, focused on REST routes. Take a look at https://github.com/deitch/booster
If your routes are RESTful:
var booster = require('booster'), express = require('express'), app = express(), db = require('./myDbSetup');
booster.init({app:app,db:db});
booster.resource('user');
app.listen(3000);
You just need to wire up the database/persistence connection layer. You can choose to customize the controller routes, or the models, or any part of it, but all optional.