encodeURIComponent on dynamic request url, node.js - node.js

I am requesting an index.djvu that fires requests for documents by id. The requests id that the index.djvu fires is Base64 encoded e.g document/page_1_1_1_k21g_MjE4MGstMTAvMTE=.djvu where the id is MjE4MGstMTAvMTE=.
I need to encode the id before the requests is sent e.g encodeURIComponent('MjE4MGstMTAvMTE=').
How can I get control over the requests that the index.djvu fires?
My code looks like this
var http = require('http');
var httpProxy = require('http-proxy');
var HttpProxyRules = require('http-proxy-rules');
var proxyRules = new HttpProxyRules({
rules: {
// This requests response index further requests explained
'.*/document': 'https://api.service.xxx/document/index.djvu?archive=21&id=2180k-10/11'
},
default: 'https://api.service.xxx/document'
});
var proxy = httpProxy.createProxyServer({
secure: false
});
proxy.on('proxyReq', function (proxyReq, req, res, options) {
proxyReq.setHeader('Authorization', 'Bearer xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx');
});
var server = {};
server.httpServer = http.createServer(function (req, res) {
var target = proxyRules.match(req);
if (target) {
return proxy.web(req, res, {
target: target
});
}
});
server.init = () => {
server.httpServer.listen(9000, () => {
console.log('\x1b[36m%s\x1b[0m', 'The HTTP server is running on port 9000');
});
}
server.init();
server.httpServer.on('error', function (err) {
console.log('Error http-server\n', JSON.stringify(err));
});
proxy.on('proxyRes', function (proxyRes, req, res) {
console.log('Status: ' + proxyRes.statusCode + ' ' + proxyRes.statusMessage);
proxyRes.on('data', function (chunk) {
console.log('Body: ' + chunk.toString('utf8'));
});
console.log('Headers received from api: ', JSON.stringify(proxyRes.headers, true, 2));
});
All help is appreciated

This solved it after several hours of war ;)
var http = require('http');
var httpProxy = require('http-proxy');
var url = require('url');
var proxy = httpProxy.createProxyServer({
target: 'https://api.xxxxxxxxxxxxxx.xxx',
secure: false
}).listen(9000);
proxy.on('proxyReq', function (proxyReq, req, res, options) {
proxyReq.setHeader('Authorization', 'Bearer xxxxxxxx-xxxx-xxxx-xxxxxxxxxxxx');
var url_parts = url.parse(req.url);
var str = url_parts.pathname;
var query = url_parts.search;
if (str) {
var path = str.split("_");
urlstring = {
page_: path[0],
vers: path[1],
subdoc: path[2],
page: path[3],
archive: path[4],
enc_id: path[5]
}
}
var rewritedPath;
if (str.includes('route')) {
rewritedPath = '/xxx' + str;
} else if (str.includes('route')) {
var index = '/xxx' + str + query;
rewritedPath = index;
} else {
var page = 'xxx' + urlstring.page_ + '_' + urlstring.vers + '_' + urlstring.subdoc + '_' + urlstring.page + '_' + urlstring.archive + '_' + encodeURIComponent(urlstring.enc_id);
rewritedPath = page;
}
proxyReq.path = rewritedPath;
});
proxy.on('error', function (err, req, res) {
console.log('Something went wrong.', err);
});
proxy.on('proxyRes', function (proxyRes, req, res) {
// console.log('Status: ' + req.url + ' ' + proxyRes.statusMessage);
// proxyRes.on('data', function (chunk) {
// console.log('Body: ' + chunk.toString('utf8'));
// });
// console.log('Headers: ', JSON.stringify(proxyRes.headers, true, 2));
});

Related

Chunk/Stream API data using Node.js

We have requirement where we need to write a node application which can read URL of image from database (approx more than million). Use image-size npm package to retrieve image meta data like height, width. Here should be an API which can list out result.
I am able to console log data but when i convert it to API, i need to chunk data so it can start appearing on browser and i'm unable to do that and need help. Here is my code
var express = require('express');
var url = require('url');
var http = require('http');
var sizeOf = require('image-size');
const sql = require('mssql');
var app = express();
var port = process.env.PORT || 3000;
const hostname = 'localhost';
var config1 = {
user: '*********',
password: '*********',
server: '*********',
database: '*******',
port: 1433,
debug: true,
options: {
encrypt: false // Use this if you're on Windows Azure
}
};
app.get('/', function(req, res){
//res.writeHead(200, { 'Content-Type': 'application/json' });
var finalResult = [];
sql.close();
sql.connect(config1, function (err) {
if (err) console.log(err);
const request = new sql.Request()
var myQuery = `select imagename from media`;
request.stream = true;
request.query(myQuery);
request.on('row', row => {
//console.log('Image : ' + row.ImageUrl);
if (row.ImageUrl != ''){
if (row.ImageUrl.indexOf('http') < 0)
row.ImageUrl = "http:" + row.ImageUrl;
var options = url.parse(row.ImageUrl);
http.get(options, function (response) {
if (response.statusCode == 200)
{
var chunks = [];
response.on('data', function (chunk) {
chunks.push(chunk);
}).on('end', function() {
var buffer = Buffer.concat(chunks);
//console.log(options.href);
//console.log(sizeOf(buffer).height);
var result = {};
result.MaskUrl = row.MaskUrl;
result.ImageUrl = options.href;
result.Height = sizeOf(buffer).height;
result.Width = sizeOf(buffer).width;
result.statusCode = 200;
finalResult.push(result);
//console.log(result);
console.log(finalResult);
res.write(result, function(){
res.end();
});
});
}
else
{
var result = {};
result.MaskUrl = row.MaskUrl;
result.ImageUrl = options.href;
result.Height = 0;
result.Width = 0;
result.statusCode = response.statusCode;
finalResult.push(result);
console.log(result);
res.write(result, function(){
res.end();
});
}
});
}
})
request.on('error', err => {
console.log ('Error for ' + row.ImageUrl );
})
request.on('done', err => {
console.log('Last Time' + finalResult.length);
})
// request.query(myQuery,(err,result) =>{
// console.log(result);
// });
});
console.log('Last Time' + finalResult.length);
res.send(finalResult);
});
app.listen(port, hostname, function(){
console.log('ImageSize running on PORT: ' + port);
});
I tried res.write, res.end without any success.
The probable reason for your problem is that here:
res.write(result, function(){
res.end();
});
You end and close the request just after the first image is read.
I would rewrite the code a little and use some functional framework, like scramjet, to stream the data straight from the DB. As Nicholas pointed out it's not super easy to run your code so I'm writing blindly - but if you fix any of my obvious error this should just work:
First:
npm install scramjet JSONStream node-fetch
Next, try this code:
var express = require('express');
var sizeOf = require('image-size');
const sql = require('mssql');
var app = express();
var port = process.env.PORT || 3000;
const hostname = 'localhost';
const {DataStream} = require('scramjet');
const fetch = require('node-fetch');
const JSONStream = require('JSONStream');
var config1 = {
user: '*********',
password: '*********',
server: '*********',
database: '*******',
port: 1433,
debug: true,
options: {
encrypt: false // Use this if you're on Windows Azure
}
};
app.get('/', function(req, res, next){
// you should consider not doing these two lines on each request,
// but I don't want to mess you code...
sql.close();
sql.connect(config1, function (err) {
if (err) next(err);
res.writeHead(200, { 'Content-Type': 'application/json' });
const request = new sql.Request();
var myQuery = `select imagename from media`;
request.stream = true;
request.query(myQuery);
const stream = new DataStream();
request.on('row', row => stream.write(row));
stream.filter(
row => row.ImageUrl !== ''
)
.map(
async row => {
if (row.ImageUrl.indexOf('http') !== 0) // url must start with http.
row.ImageUrl = "http:" + row.ImageUrl;
const response = await fetch(row.ImageUrl);
let size = {width:0, height:0};
if (response.status === 200) {
const buffer = await response.buffer();
size = sizeOf(buffer);
}
return {
MaskUrl: row.MaskUrl,
ImageUrl: row.ImageUrl,
Height: size.height,
Width: size.width,
statusCode: response.status
};
}
)
.pipe(
JSONStream.stringify()
).pipe(
res
);
request.on('error', () => {
res.writeHead(500, { 'Content-Type': 'application/json' });
stream.end("{error:true}");
});
request.on('done', () => stream.end());
});
});
app.listen(port, hostname, function(){
console.log('ImageSize running on PORT: ' + port);
});

Node.js http-proxy inside cluster worker

I build a sample code in node js
var cluster = require("cluster"),
http = require("http"),
express = require('express'),
port = parseInt(process.argv[2]||8001),
servers = ['http://127.0.0.1:800821', 'http://127.0.0.1:800831'];;
if (cluster.isMaster) {
console.log('Master ' + process.pid + ' has started.');
var numWorkers = require('os').cpus().length;
console.log('Master cluster setting up ' + numWorkers + ' workers...');
for(var i = 0; i < 1; i++) {
cluster.fork();
}
cluster.on('online', function(worker) {
console.log('Worker ' + worker.process.pid + ' is online');
});
cluster.on('exit', function(worker, code, signal) {
console.log('Worker ' + worker.process.pid + ' died with code: ' + code + ', and signal: ' + signal);
console.log('Starting a new worker');
cluster.fork();
});
} else {
var httpProxy = require('http-proxy');
var proxy = httpProxy.createProxyServer();
var count = 0;
// Workers share the TCP connection in this server
var app = express();
app.get('/', function (req, res) {
console.log('Cluster => ' + process.pid);
loadBalanceProxy(req,res);
}).listen(port);
var currentServer = 1;
function loadBalanceProxy(req, res){
var cur = currentServer%servers.length;
currentServer++;
var target = servers[cur];
console.log("Proxy => " + target);
proxy.web(req, res, {
target: target
});
}
}
http.createServer(function (req, res) {
res.writeHead(200, { 'Content-Type': 'text/plain' });
res.write('request successfully proxied to: ' + req.url + '\n' + JSON.stringify(req.headers, true, 2));
res.end();
}).listen(800831);
http.createServer(function (req, res) {
res.writeHead(200, { 'Content-Type': 'text/plain' });
res.write('request successfully proxied to: ' + req.url + '\n' + JSON.stringify(req.headers, true, 2));
res.end();
}).listen(800821);
In this sample, I want to create proxy server inside cluster worker and this give me error bind EADDRINUSE null:800831
I want to know can I create http-proxy inside cluster worker. If I can't then there's solution for load balance between machines ?
I create a proxy reverse exemple proxy reverse inside cluster and i create 3 servers in another files, it works for me (dont forget to run the servers separately for example on windows you launch servers in 4 cmd, 1 cmd for proxy and other (3 cmd) for servers )
// var https = require('https'); scure
var http = require('http');
var proxy = require('http-proxy');
var cluster = require('cluster');
var fs = require('fs');
var request = require('request');
// const numCPUs = require('os').cpus().length;
var numCPUs = 4;
if (cluster.isMaster) {
for (var i = 0; i < numCPUs; i++) {
cluster.fork();
}
cluster.on('fork', (worker) => {
console.log('worker ' + worker.process.pid);
});
cluster.on('exit', function(worker, code, signal) {
console.log('Worker ' + worker.process.pid + ' died with code: ' + code + ', and signal: ' + signal);
console.log('Starting a new worker');
cluster.fork();
});
} else {
startProxyReverse();
}
function startProxyReverse() {
http.globalAgent.maxSockets = 10240;
// Define the servers to load balance.
var servers = [{
host: '127.0.0.1',
port: 8001
}, {
host: '127.0.0.1',
port: 8003
}, {
host: '127.0.0.1',
port: 8002
}];
var failoverTimer = [];
// load the SSL cert
// var ca = [
// fs.readFileSync('./certs/PositiveSSLCA2.crt'),
// fs.readFileSync('./certs/AddTrustExternalCARoot.crt')
// ];
// var opts = {
// ca : ca,
// key : fs.readFileSync('./certs/example_wild.key'),
// cert : fs.readFileSync('./certs/STAR_example_com.crt')
// };
// Create a proxy object for each target.
var proxies = servers.map(function(target) {
return new proxy.createProxyServer({
target: target
// ws : true,
// xfwd : true,
// ssl : opts,
// down : false
});
});
/**
* Select a random server to proxy to. If a 'server' cookie is set, use that
* as the sticky session so the user stays on the same server (good for ws fallbacks).
* #param {Object} req HTTP request data
* #param {Object} res HTTP response
* #return {Number} Index of the proxy to use.
*/
var selectServer = function(req, res) {
var index = -1;
var i = 0;
// Check if there are any cookies.
if (req.headers && req.headers.cookie && req.headers.cookie.length > 1) {
var cookies = req.headers.cookie.split('; ');
for (i = 0; i < cookies.length; i++) {
if (cookies[i].indexOf('server=') === 0) {
var value = cookies[i].substring(7, cookies[i].length);
if (value && value !== '') {
index = value;
break;
}
}
}
}
// Select a random server if they don't have a sticky session.
if (index < 0 || !proxies[index]) {
index = Math.floor(Math.random() * proxies.length);
}
// If the selected server is down, select one that isn't down.
if (proxies[index].options.down) {
index = -1;
var tries = 0;
while (tries < 5 && index < 0) {
var randIndex = Math.floor(Math.random() * proxies.length);
if (!proxies[randIndex].options.down) {
index = randIndex;
}
tries++;
}
}
index = index >= 0 ? index : 0;
// Store the server index as a sticky session.
if (res) {
res.setHeader('Set-Cookie', 'server=' + index + '; path=/');
}
return index;
};
/**
* Fired when there is an error with a request.
* Sets up a 10-second interval to ping the host until it is back online.
* There is a 10-second buffer before requests start getting blocked to this host.
* #param {Number} index Index in the proxies array.
*/
var startFailoverTimer = function(index) {
if (failoverTimer[index]) {
return;
}
failoverTimer[index] = setTimeout(function() {
// Check if the server is up or not
request({
url: 'http://' + proxies[index].options.target.host + ':' + proxies[index].options.target.port,
method: 'HEAD',
timeout: 10000
}, function(err, res, body) {
failoverTimer[index] = null;
if (res && res.statusCode === 200) {
proxies[index].options.down = false;
console.log('Server #' + index + ' is back up.');
} else {
proxies[index].options.down = true;
startFailoverTimer(index);
console.log('Server #' + index + ' is still down.');
}
});
}, 10000);
};
// Select the next server and send the http request.
var serverCallback = function(req, res) {
console.log('Process ' + process.pid + ' is listening to all incoming requests');
var proxyIndex = selectServer(req, res);
console.log(proxyIndex);
var proxy = proxies[proxyIndex];
proxy.web(req, res);
proxy.on('error', function(err) {
startFailoverTimer(proxyIndex);
});
};
console.log('create server');
// var server = http.createServer(opts, serverCallback); scure server
var server = http.createServer(serverCallback);
// http.createServer(serverCallback).listen(8000);
// Get the next server and send the upgrade request.
// server.on('upgrade', function (req, socket, head) {
// var proxyIndex = selectServer(req);
// var proxy = proxies[proxyIndex];
// proxy.ws(req, socket, head);
// proxy.on('error', function (err, req, socket) {
// socket.end();
// startFailoverTimer(proxyIndex);
// });
// });
server.listen(8000);
// server.listen(443); scure port
// var proxi = proxy.createServer();
// http.createServer(function (req, res) {
// var target = {
// target : servers.shift()
// };
// console.log('Process ' + process.pid + ' is listening to all incoming requests');
// console.log('balancing request to: ', target);
// proxi.web(req, res, target);
// servers.push(target.target);
// }).listen(8000);
}
Ports should in 1-65535 range.

Why is this not working, And how do you debug code in nodejs?

First I'm trying to learn nodejs, and for that I am writing like a router. As you have in express.
This is my code:
function sirus() {
var util = utilFuncs(),
paths = {};
this.router = util.handleReq;
this.con = {
get: function (path, fn, options) {
options = (options || {}).method = "GET";
util.makeRequest(path, fn, options);
},
post: function (path, fn, options) {
options = (options || {}).method = "POST";
util.makeRequest(path, fn, options);
}
};
this.req = {
get: function (path, fn) {
util.addPath("GET", path, fn);
},
post: function (path, fn) {
util.addPath("POST", path, fn);
}
};
function utilFuncs() {
function handleReq(req, res) {
var url = parsePath(req.url);
var path = paths[req.method + url];
// console.log(req.url, url +' requested');
if (typeof path != "function") {
res.writeHead(404);
} else {
path(req, res);
}
res.end();
}
function addPath(type, path, callback) {
// add path as a key of object for easier look up, root=/, /a=/a, /a/=/a, /a?=/a, /a/?..=/a so there are no duplicates path=parsePath(path);
paths[type + path] = callback;
}
function parsePath(path) {
path = url.parse(path).pathname;
if ((/[^\/]+\/(?=$)/igm).test(path)) path = path.substring(0, path.length - 1);
return path;
}
function makeRequest(path, fn, options) {
var urls = url.parse(path);
var d = {
host: null,
hostname: null,
method: "GET",
path: '/',
port: 80,
headers: {},
auth: null,
agent: false,
keepAlive: false
};
for (var k in options) d[k] = options[k];
d.host = urls.host;
d.hostname = urls.hostname;
d.path = urls.pathname;
d.headers['Content-Type'] = 'application/x-www-form-urlencoded';
d.headers['Content-Length'] = ((d || {}).body || {}).length || '';
var req = http.request(options, function (res) {
// console.log('STATUS: ' + res.statusCode);
// console.log('HEADERS: ' + JSON.stringify(res.headers));
res.setEncoding('utf8');
var data = '';
res.on('data', function (chunk) {
data += chunk;
});
res.on('end', function (chunk) {
data += chunk;
});
res.on('response', function () {
fn(res);
});
});
req.on('error', function (e) {
console.log('problem with request: ' + e.message);
});
req.write(d.body);
req.end();
}
return {
makeRequest: makeRequest,
handleReq: handleReq,
addPath: addPath
};
}
}
and i use it like this:
var http = require('http'),
url = require('url'),
app = new sirus();
http.createServer(function (req, res) {
app.router(req, res);
}).listen(80, '127.0.0.1');
app.req.get('/', function (req, res) {
res.writeHead(200, {'Content-Type': 'text/html'});
var link = "https://www.reddit.com/";
res.write('Click here');
});
app.con.get('http://www.google.com/', function (res) {
console.log('from req: ' + res);
});
The error i get is The First argument must be string or buffer
Receiving part works correctly, but when i started to add make request part something isn't right.
Also since I'm new to JS and Nodejs. I'd like general advice or anything that catch your eye something that i can be improved about this code. Since I'm note sure i am doing things the best way.
On line 85
req.write(d.body);
there is no member named "body" in the "d" object.
1 - Why is this not working - you get exactly error that tells you why it is not working. If you check more details about error it shows the file and which line error happened at. Perhaps the arguments you pass to function call are not what Express is expecting.
2 - How to debug - look at node.js package called nodev.

Node.js, Proxy HTTPS traffic without re-signing

I'm building a proxy using Node.js to be run on my local machine that will log all domains accessed. Kind of the same way Fiddler works, but my program is more simple, I don't need to look at the data or decrypt anything.
I got this working fine for HTTP but for HTTPS it resigns the traffic with the self-signed certificate provided. This results in that the browser displays a warning. The same thing doesn't happen in fiddler unless you choose to decrypt HTTPS traffic.
So my question is: How do I proxy HTTPS traffic using Node.js so that it is completely transparent for the user?
This is the code I'm using right now, using the Node.js http-proxy. Based on the Github project, proxy-mirror.
var httpProxy = require('http-proxy'),
https = require('https'),
connect = require('connect'),
logger = connect.logger('dev'),
EventEmitter = require('events').EventEmitter,
util = require('util'),
Iconv = require('iconv').Iconv,
convertBuffer = require('./convertBuffer'),
fs = require('fs'),
net = require('net'),
url = require('url'),
path = require('path'),
certDir = path.join(__dirname, '/../cert'),
httpsOpts = {
key: fs.readFileSync(path.join(certDir, 'proxy-mirror.key'), 'utf8'),
cert: fs.readFileSync(path.join(certDir, 'proxy-mirror.crt'), 'utf8')
};
var Session = function (sessionId, req, res) {
EventEmitter.call(this);
var that = this;
this.id = req._uniqueSessionId = res._uniqueSessionId = sessionId;
this.request = req;
this.request.body = {asString: null, asBase64: null};
this.response = res;
this.response.body = {asString: null, asBase64: null};
this.state = 'start';
var hookInResponseWrite = function () {
var response = that.response;
var _write = response.write;
var output = [];
response.write = function (chunk, encoding) {
output.push(chunk);
_write.apply(response, arguments);
};
return output;
}, hookInRequestData = function () {
var request = that.request,
output = [];
request.on('data', function (chunk, encoding) {
output.push(chunk);
});
request.on('end', function () {
var buffersConcatenated = Buffer.concat(output);
request.body.asString = buffersConcatenated.toString();
that.emit('request.end', that);
});
return output;
};
this.response.bodyBuffers = hookInResponseWrite();
this.request.bodyBuffers = hookInRequestData();
this.ended = function () {
var buffersConcatenated = Buffer.concat(this.response.bodyBuffers);
this.response.body.asString = convertBuffer.convertEncodingContentType(buffersConcatenated,this.response.getHeader('content-type') || '');
this.response.body.asBase64 = buffersConcatenated.toString('base64');
this.removeAllListeners();
};
};
util.inherits(Session, EventEmitter);
Session.extractSessionId = function (req) {
return req._uniqueSessionId;
};
var SessionStorage = function () {
var sessionHash = {},
sessionIdCounter = 0,
nextId = function () {
return sessionIdCounter += 1;
};
this.startSession = function (req, res) {
var sessionId = nextId(), session;
sessionHash[sessionId] = session = new Session(sessionId, req, res);
return session;
};
this.popSession = function (req) {
var sessionId = Session.extractSessionId(req),
session = sessionHash[sessionId];
delete sessionHash[sessionId];
return session;
};
};
var ProxyServer = function ProxyServer() {
EventEmitter.call(this);
var proxyPort = 8888,
secureServerPort = 8887,
parseHostHeader = function (headersHost, defaultPort) {
var hostAndPort = headersHost.split(':'),
targetHost = hostAndPort[0],
targetPort = parseInt(hostAndPort[1]) || defaultPort;
return {hostname: targetHost, port: targetPort, host: headersHost};
},
sessionStorage = new SessionStorage(),
adjustRequestUrl = function(req){
if (requestToProxyMirrorWebApp(req)) {
req.url = req.url.replace(/http:\/\/localhost:8889\//, '/');
}
req.url = url.parse(req.url).path;
},
proxyServer = httpProxy.createServer({
changeOrigin: true,
enable: {
xforward: false
}
}, function (req, res, proxy) {
var parsedHostHeader = parseHostHeader(req.headers['host'], 80),
targetHost = parsedHostHeader.hostname,
targetPort = parsedHostHeader.port;
req.originalUrl = req.url;
adjustRequestUrl(req);
logger(req, res, function () {
proxy.proxyRequest(req, res, {
host: targetHost,
port: targetPort
});
})
}),
proxy = proxyServer.proxy,
secureServer = https.createServer(httpsOpts, function (req, res) {
var parsedHostHeader = parseHostHeader(req.headers.host, 443);
// console.log('secure handler ', req.headers);
req.originalUrl = req.url;
if(!req.originalUrl.match(/https/)){
req.originalUrl = 'https://' + parsedHostHeader.host + req.url;
}
adjustRequestUrl(req);
logger(req, res, function () {
proxy.proxyRequest(req, res, {
host: parsedHostHeader.hostname,
port: parsedHostHeader.port,
changeOrigin: true,
target: {
https: true
}
});
});
}),
listening = false,
requestToProxyMirrorWebApp = function (req) {
var matcher = /(proxy-mirror:8889)|(proxy-mirror:35729)/;
return req.url.match(matcher) || (req.originalUrl && req.originalUrl.match(matcher));
};
[secureServer,proxyServer].forEach(function(server){
server.on('upgrade', function (req, socket, head) {
// console.log('upgrade', req.url);
proxy.proxyWebSocketRequest(req, socket, head);
});
});
proxyServer.addListener('connect', function (request, socketRequest, bodyhead) {
//TODO: trying fixing web socket connections to proxy - other web socket connections won't work :(
// console.log('conenct', request.method, request.url, bodyhead);
var targetPort = secureServerPort,
parsedHostHeader = parseHostHeader(request.headers.host);
if(requestToProxyMirrorWebApp(request)){
targetPort = parsedHostHeader.port;
}
var srvSocket = net.connect(targetPort, 'localhost', function () {
socketRequest.write('HTTP/1.1 200 Connection Established\r\n\r\n');
srvSocket.write(bodyhead);
srvSocket.pipe(socketRequest);
socketRequest.pipe(srvSocket);
});
});
this.emitSessionRequestEnd = function (session) {
this.emit('session.request.end', session);
};
this.startSession = function (req, res) {
if (requestToProxyMirrorWebApp(req)) {
return;
}
var session = sessionStorage.startSession(req, res);
this.emit('session.request.start', session);
session.on('request.end', this.emitSessionRequestEnd.bind(this));
};
this.endSession = function (req, res) {
if (requestToProxyMirrorWebApp(req)) {
return;
}
var session = sessionStorage.popSession(req);
if (session) {
session.ended();
this.emit('session.response.end', session);
}
};
this.start = function (done) {
done = done || function () {
};
proxy.on('start', this.startSession.bind(this));
proxy.on('end', this.endSession.bind(this));
proxyServer.listen(proxyPort, function () {
secureServer.listen(secureServerPort, function () {
listening = true;
done();
});
});
};
this.stop = function (done) {
done = done || function () {
};
proxy.removeAllListeners('start');
proxy.removeAllListeners('end');
if (listening) {
secureServer.close(function () {
proxyServer.close(function () {
listening = false;
done();
});
});
}
};
};
util.inherits(ProxyServer, EventEmitter);
module.exports = ProxyServer;

NodeJS + Express: How to use sessions variables in other methods. (Session-variable: undefined)

I'm using NodeJS 0.10.18 and Express 3.4.0 for a webserver to work with an PhoneGap application.
I want to use Session Variables/Sessions to store the users Username to use it in other methods.
When i login in the login method, the username is stored in req.session.name (it is set because i can print it to the console). But later on when i want to use it in the reserve method the req.session.name variable is suddenly undefined.
Can you tell me what i'm doing wrong?
Here's my code:
//NodeJS Modules
var http = require('http');
var express = require("express");
//Variables
var app = express();
var listenport = '8123';
var Username = "";
var Password = "";
//Application configuration
app.configure(function(){
app.use(express.cookieParser('S3CRE7'));
app.use(express.cookieSession());
app.use(app.router);
});
//Create header for every HTTP response
app.all("*", function(req, res, next) {
res.writeHead(200, {'Content-Type': 'text/plain', 'Access-Control-Allow-Origin': '*'});
next();
});
//Login
app.post("/MobileApplication/login", function(req, res) {
//Response 0 = correct
var loginUsername = req.param('Username');
//VALIDATE
//STORE IN SESSION
req.session.name = loginUsername;
console.log(req.session.name);
res.end("0");
});
//Reservation
app.post("/MobileApplication/reserve", function(req, res) {
var name = req.session.name;
console.log(name);
res.end("0");
});
//If the url isn't valid respond with 404
app.all("*", function(request, response) {
response.end("404!");
});
//Listen on listenport
http.createServer(app).listen(listenport);
Phonegap ajax login request:
jQuery.ajax({
url: "http://" + serverip + ":" + serverpoort + "/MobileApplication/login?Username=" + Username + "&Password=" + Password + "",
type: "POST",
beforeSend: function(data) {
console.log("login - sending");
},
success: function(data) {
console.log("login - succes!");
if (data === "0") {
$('input[type="checkbox"]').filter('#checkbox-1').each(function() {
if ($(this).is(':checked')) {
// perform operation for checked
window.localStorage.setItem("Username", Username);
window.localStorage.setItem("Password", Password);
$.mobile.navigate("#customers", {transition: "slide"});
}
else {
// perform operation for unchecked
window.localStorage.setItem("Username", "");
window.localStorage.setItem("Password", "");
$.mobile.navigate("#customers", {transition: "slide"});
}
});
}
if (data === "1") {
navigator.notification.alert(
'The username you have entered does not exist.', // message
doNothing,
'Error', // title
'Ok' // buttonName
);
}
if (data === "2") {
navigator.notification.alert(
'You have entered a wrong password.', // message
doNothing,
'Error', // title
'Ok' // buttonName
);
}
},
error: function(a, b, c) {
alert("login - error: " + a.toString() + " " + b.toString() + " " + c.toString());
navigator.notification.alert(
"login - error: " + a.toString() + " " + b.toString() + " " + c.toString(), // message
doNothing,
'Error', // title
'Ok' // buttonName
);
}
});

Resources