Hijack response before sent to client - node.js

I have follow codes to be used as middlewares
module.exports=function(callback) {
callbacks.push(callback);
return function(req,res,next) {
if (!res.hijacked) {
res.hijacked=true;
} else {
return next();
}
var send=res.send;
res.send=function(data) {
var body=data instanceof Buffer ? data.toString() : data;
var requests=[];
requests.push(function(next) {
callbacks[0](req,res)(body,doneWrapper(body,next));
});
for (var i=1;i<callbacks.length;i++) {
var hijackCallback=callbacks[i];
requests.push(function(result,next) {
hijackCallback(req,res)(result,doneWrapper(result,next));
});
}
var that=this;
async.waterfall(requests,function(err,result) {
send.call(that,result);
requests=null;
body=null;
that=null;
});
};
next();
};
};
An example of usage is as following:
module.exports=function() {
return hijack(function() {
return function(result,done) {
var json={};
try {
json=JSON.parse(result);
} catch(e) {
return done();
}
if (!_.isArray(json)) {
return done();
}
var sorted=_(json).sortBy(function(item) {
if (_.isObject(item.information)) {
return item.information.rangeIndex1 || 999;
} else {
return 1001;
}
});
done(sorted);
}
});
};
It worked fine initially as middlewares in routes.
However,When i try to make it as app.use(hijackMiddleware()). Something went wrong, I got this Can't set headers after they are sent error.
There is no problem when used as middlewares in routes,though.

Have you consider using express-interceptor? Is really easy to use:
var express = require('express');
var cheerio = require('cheerio');
var interceptor = require('express-interceptor');
var app = express();
var finalParagraphInterceptor = interceptor(function(req, res){
return {
// Only HTML responses will be intercepted
isInterceptable: function(){
return /text\/html/.test(res.get('Content-Type'));
},
// Appends a paragraph at the end of the response body
intercept: function(body, send) {
var $document = cheerio.load(body);
$document('body').append('<p>From interceptor!</p>');
send($document.html());
}
};
})
// Add the interceptor middleware
app.use(finalParagraphInterceptor);
app.use(express.static(__dirname + '/public/'));
app.listen(3000);

Related

How to I dynamically insert key and value in JSON in the response of NodeJs API

This is the Input I am providing
{
"cities" : [
"kolkata",
"mumbai",
"chennai"
]
}
and this is the response I am receiving.
{
"weather": [
{
"chennai": "30C"
},
{
"mumbai": "27C"
},
{
"kolkata": "26C"
}
]
}
I want a response somewhat like
{
"weather" : {
"kolkata" : "26C",
"mumbai": "27C",
"chennai": "30C"
}
}
My code is as follows.
const express = require('express');
const router = express.Router();
const bodyParser = require('body-parser');
const request = require('request');
const app = express();
const apiKey = 'c6068c4018def9330b01366aed03b08e';
app.use(express.static('public'));
app.use(bodyParser.json());
router.post('/getWeather', function (req, res) {
let cities = req.body.cities;
let weatherJson = [];
for(let i=0; i<cities.length; i++)
{
let city = cities[i];
let url = `http://api.weatherstack.com/current?access_key=${apiKey}&query=${city}`;
request(url, function (response, body) {
if (response) {
return res.json({ error: response });
}
let weather = JSON.parse(body.body);
if (weather.current == undefined) {
return res.json({ error: "somethin went wrong!" });
}
let weatherText = `${weather.current.temperature}C`;
weatherJson.push({ [city] : weatherText });
if(weatherJson.length == cities.length) {
console.log("here");
res.json({"weather": weatherJson});
}
});
}
});
app.use('/', router);
app.listen(3000, function () {
console.log('Example app listening on port 3000!')
});
I have tried adding as hashmap, adding in array format then using stringify at the response point, but nothing seems to work. I just want to convert the format of the response to the desirable one with as minimalistic change in the code as possible. Please help.
You have a few issues, first off you're storing weatherJson (response) as an array when you say you want it to be a map.
here's how I would implement this:
router.post("/getWeather", async function (req, res) {
let cities = req.body.cities;
let weatherJson = {};
for (let i = 0; i < cities.length; i++) {
let city = cities[i];
let url = `http://api.weatherstack.com/current?access_key=${apiKey}&query=${city}`;
try {
const response = await fetch(url);
let weather = JSON.parse(response.body);
if (weather.current == undefined) {
return res.json({ error: "somethin went wrong!" });
}
let weatherText = `${weather.current.temperature}C`;
weatherJson[city] = weatherText;
} catch (err) {
return res.json({ error: err });
}
}
res.json({ weather: weatherJson });
});
You should use node-fetch instead of request which is obsolete. It does the same thing but much cleaner with promises instead of callbacks.
try creating an object instead of an array.
const express = require('express');
const router = express.Router();
const bodyParser = require('body-parser');
const request = require('request');
const app = express();
const apiKey = 'c6068c4018def9330b01366aed03b08e';
app.use(express.static('public'));
app.use(bodyParser.json());
router.post('/getWeather', function (req, res) {
let cities = req.body.cities;
let weatherJson = {};
for(let i=0; i<cities.length; i++)
{
let city = cities[i];
let url = `http://api.weatherstack.com/current?access_key=${apiKey}&query=${city}`;
request(url, function (response, body) {
if (response) {
return res.json({ error: response });
}
let weather = JSON.parse(body.body);
if (weather.current == undefined) {
return res.json({ error: "somethin went wrong!" });
}
let weatherText = `${weather.current.temperature}C`;
weatherJson[city]=weatherText;
if(Object.keys(weatherJson).length == cities.length) {
console.log("here");
res.json({"weather": weatherJson});
}
});
}
});
app.use('/', router);
app.listen(3000, function () {
console.log('Example app listening on port 3000!')
});

How do I make sure socket.id is the same on the server and the client after a page reload?

I am writing a Proof Of Concept (for at least 2 months now) that uses Node cluster (workers), Redis and socket.io.
Socket.io is not in use for chat in this instance - just back to front communication. Ajax is not an option.
I am using pub/sub for redis and have that piece working (I think). At least the values returned from pubClient.get('key') are correct.
When I make a request from the front end and do not navigate or reload the page in any way, things work perfectly - I can make 10 requests and 10 responses are received.
Conversely, when I navigate, the same is not true - and I need to deliver the results no matter how much someone navigates on the front end.
It seems there is a disconnect after a reload. In both consoles - Dev Tools and node js, the socket ids are the same. I'm really scratching my head on this one!
Any help out there?
So, for some mainly socket.io code:
CLIENT:
socket = io('https://' + location.hostname + ':4444/', {
transports: ['websocket', 'polling'],
secure: true,
});
socket.on('download', function(data){// after reload, this never hits
console.log('DOWNLOAD '+ data.download);
});
var pkgs = ['y14Vfk617n6j', 'My77gWYmBLxT', 'IYd6dL9UoXkx'];
if(pkgs.length > 0){
for(var i = 0; i < pkgs.length; i++){
socket.emit('get-request', pkgs[i]);
}
}
SERVER:
var cluster = require('cluster');
var express = require('express');
var numCPUs = require('os').cpus().length;
const { setupMaster, setupWorker } = require("#socket.io/sticky");
const { createAdapter, setupPrimary } = require("#socket.io/cluster-adapter");
var app = express();
const https = require('https');
const { Server } = require("socket.io");
const Redis = require("ioredis");
const sock_nodes = [
{port: 6379, host: '192.168.0.41'},
{port: 6380, host: '192.168.0.34'},
{port: 6381, host: '192.168.0.35'},
{port: 6379, host: '192.168.0.34'},
{port: 6380, host: '192.168.0.35'},
{port: 6381, host: '192.168.0.41'}
];
const port = 4444;
const httpServer = https.createServer(options, app);
const io = new Server(httpServer, {maxHttpBufferSize: 10240000});
const pubClient = new Redis.Cluster(sock_nodes, {
redisOptions: {
password: 'my secret!'
}
});
const subClient = pubClient.duplicate(); // I am not actually using this - should I be?
if (cluster.isMaster) {
for (var i = 0; i < numCPUs; i++) {
// Create a worker
cluster.fork();
}
cluster.on("exit", (worker) => {
console.log(`Worker PID ${worker.process.pid} died`);
var w = cluster.fork();
console.log('WORKER %d died (%s). restarting...', worker.process.pid, worker.state);
w.on('message', function(msg){
console.log("Message Received : " , msg);
});
});
} else {
app.use((req, res, next) => {
var reqip = req.headers['x-real-ip'] || req.headers['x-forwarded-for'] || req.connection.remoteAddress;
//~ console.log(reqip, md5(reqip));
var sess = parseCookies(req, 'session_state');
if(!sess){
res.cookie('session_state', md5(reqip));
}
next();
});
app.get('/', (req, res) => {
getSession(req, res, function(sess){
getPub('currSockets', sess, function(err, socket){
res.render("pages/shared/index", {'ns': sess, 'socket': socket});
});
});
});
});
app.get('/start', function(req, res){
getSession(req, res, function(sess){
getPub('currSockets', sess, function(err, socket){
res.render("pages/shared/start", {'ns': sess, 'socket': socket});
});
});
});
io.on('connection', function (socket) {
var currUser = parseCookies(socket.request, 'session_state');
socket.join(currUser);
getPub('currSockets', currUser, function(err, currSockets){
if (currSockets) {
currSockets = JSON.parse(currSockets);
if (currSockets[currUser]) {
if (currSockets[currUser].stream) {
currSockets[currUser].sock = socket.id;
setCurrSockets(currSockets, currUser, null, function(cSocks){
});
}
}
}
});
socket.on('get-request', function(data){ // can be one or many requests
// there is a similar, currently irrelevant, socket.on('new-request') that is left out here
if(data){
getPub('currSockets', currUser, function(err, currSockets){
currSockets = JSON.parse(currSockets);
if(currSockets){
if(currUser){
if(currSockets[currUser]){
if(currSockets[currUser].stream){
var str = Object.keys(currSockets[currUser].stream);
for(var i = 0; i < str.length; i++){
if(str[i] !== 'sock'){
if(!currSockets[currUser].stream[str[i]]){
delete currSockets[currUser].stream[str[i]];
setCurrSockets(currSockets, currUser, null, function(cSocks){
checkCurrSockets(currUser, data, socket);
});
}
}
}
}
}
}
}
});
}
});
});
httpServer.listen(port, () => {
logs(__line__, `Worker ${process.pid} listening on ${port}`);
});
}
function existsPub(key, cb){
return pubClient.exists(key, cb);
}
function setPub(key, val, cb){
if(val === JSON.stringify({})){
return pubClient.get(key, cb);
}
return pubClient.set(key, val, cb);
}
function getPub(key, currUser, cb){
existsPub(key, function(err, reply){
if(reply === 1){
return pubClient.get(key, cb);// always getting an old socket.id
}
});
}
// Here is the piece that doesn't work after reloading the page
function ioEmit (currSock, target, payload) {
io.to(currSock).emit(target, payload); // doesn't work after page reload
}
// end piece where after reload does not work
getPub('currSockets', currUser, function(err, currSockets){
if( currSockets){
currSockets = JSON.parse(currSockets);
ioEmit(currUser, 'download', {'download': currSockets[currUser].stream[data]);
}
});
function parseCookies (req, name) {
var list = {}, rc;
rc && rc.split(';').forEach(function( cookie ) {
var parts = cookie.split('=');
list[parts.shift().trim()] = decodeURI(parts.join('='));
});
return list[name];
}
function getSession(req, res, callback) {
var sess = false;
if(req.headers) {// handle req
var reqip = req.headers['x-real-ip'] || req.headers['x-forwarded-for'] || req.connection.remoteAddress;
if(req.headers.cookie){
sess = req.headers.cookie.split('=')[1].split(';')[0];
} else {
res.cookie('session_state', md5(reqip));
}
return callback(sess);
} else if(req.request) {// handle socket
//~ console.log('req.request.headers.cookie', req.request.headers.cookie.split('=')[1]);
if(req.request.headers.cookie){
sess = req.request.headers.cookie.split('=')[1].split(';')[0];
//~ req.emit('join', sess);
//~ callback({[sess]: {'sock': req.id}});
callback(req.id);
}
} else {
return callback(null);
}
}
function setCurrSockets(currSockets, currUser, data, cb){
if(Object.keys(currSockets[currUser].stream).length > 0){
if(data){
if(ready(currSockets, currUser, data)){
delete currSockets[currUser].stream[data];// it appears that setCurrSockets is getting called too soon
}
}
setPub('currSockets', JSON.stringify(currSockets), function(err){
});
if(typeof cb === 'function'){
setTimeout(() => {
getPub('currSockets', currUser, function(err, cSocks){
cb(cSocks);// updated callback to return cSocks
}, 2000);
});
}
} else {
currSockets[currUser].stream = {};
setPub('currSockets', JSON.stringify(currSockets), function(err){
if(err){
} else {
if(typeof cb === 'function'){
cb(currSockets);// updated callback to return cSocks
}
}
});
}
}
figured this out. The problem was in here:
for(var i = 0; i < str.length; i++){
if(str[i] !== 'sock'){
>>>> if(!currSockets[currUser].stream[str[i]]){ // never true
// delete currSockets[currUser].stream[str[i]];
setCurrSockets(currSockets, currUser, null, function(cSocks){
checkCurrSockets(currUser, data, socket);
});
}
}
}
so I commented the for loop and kept the setCurrSockets part and it works.
Just thought I would share, in case someone else tries to use redis, node cluster and socket.io together. As #jfreind00 said, you should use an authentication system with a randomly gen'd string for storing cookies.

The request won't go through api path

I'm making a post request with jquery to '/get_access_token' url. but it is not going through. In postman the request is stuck in 'Sending'. Below I'm adding the code.
app.js
const myRouter = require('./src/routes/myRouter ');
app.use('/get_access_token', myRouter );
myRouter,js
//this is inside myRouter
const express = require('express');
const myRouter= express.Router();
const myController = require('../controllers/myController');
function router() {
debug('inside router');
const { getAccessToken } = myController();
debug(getAccessToken);
//from here it is not going down
myRouter.route('/get_access_token').post((request) => {
debug('inside api call');
const result = getAccessToken(request);
});
}
module.exports = router;
myController.js
const client = require('path to client');
function myController() {
function getAccessToken(request) {
debug('inside getAccessToken');
const PUBLIC_TOKEN = request.body.public_token;
Promise((resolve, reject) => {
client.exchangePublicToken(PUBLIC_TOKEN, (error, tokenResponse) => {
if (error != null) {
reject(new Error('Could not get access token'));
}
const ACCESS_TOKEN = tokenResponse.access_token;
const ITEM_ID = tokenResponse.item_id;
debug(ACCESS_TOKEN);
debug(ITEM_ID);
resolve('Access Token was acquired succesfully');
});
});
}
return {
getAccessToken
};
}
module.exports = myController;
jquery request, only the portion when there is a public token
onSuccess: function(public_token) {
debugger;
$.post('/get_access_token', {
public_token: public_token
}, function() {
$('#container').fadeOut('fast', function() {
$('#intro').hide();
$('#app, #steps').fadeIn('slow');
});
});
}
This is the issue
module.exports = router;
Router is the function, not the router actually, it cannot work.
It can theoretically work if you exports the myRouter, but you have to define it properly.
I suggest to find some "express boilerplate" on internet, make it work and then just update that code to your needs

Solve Socket.io connection in a external module with expressjs

I have the following case: When I try to connect the module called 'Signaling-Server.js'
in the view of html the console says: GET ERROR [HTTP/1.1 400 Bad Request 1ms]
But this only happens when I add these Module. When I try to connect without him the socket.io connections works perfectly.
app.js
//Modules
var express = require("express"),
http = require("http"),
morgan= require("morgan"),
bodyParser = require('body-parser'),
methodOverride = require('method-override'),
app = express(),
server = http.createServer(app),
io = require("socket.io").listen(server);
app.use(express.static(__dirname + '/public'));
app.use(morgan('dev'));
app.use(bodyParser.urlencoded({ extended:false}));
app.use(bodyParser.json());
app.use(methodOverride());
app.set("views",__dirname + "/views");
//I need to 'onnect with this module
//require('./Signaling-Server.js')(myServerOrPort);
require('./Signaling-Server.js')(server);
//Server is ready
server.listen(3000);
The code of Signaling-Server is here (Cortesy of MuazKhan Proyect "RTCMultiConnection")
Signaling-Server.js
// Muaz Khan - www.MuazKhan.com
// MIT License - www.WebRTC-Experiment.com/licence
// Documentation - github.com/muaz-khan/RTCMultiConnection
module.exports = exports = function(app, socketCallback) {
var io = require('socket.io').listen(app, {
log: false,
origins: '*:*'
});
io.set('transports', [
'websocket', // 'disconnect' EVENT will work only with 'websocket'
'xhr-polling',
'jsonp-polling'
]);
var listOfUsers = {};
var shiftedModerationControls = {};
var ScalableBroadcast;
io.sockets.on('connection', function(socket) {
var params = socket.handshake.query;
var socketMessageEvent = params.msgEvent || 'RTCMultiConnection-Message';
if (params.enableScalableBroadcast) {
if (!ScalableBroadcast) {
ScalableBroadcast = require('./Scalable-Broadcast.js');
}
var singleBroadcastAttendees = params.singleBroadcastAttendees;
ScalableBroadcast(socket, singleBroadcastAttendees);
}
socket.userid = params.userid;
listOfUsers[socket.userid] = {
socket: socket,
connectedWith: {},
isPublic: false, // means: isPublicModerator
extra: {}
};
socket.on('extra-data-updated', function(extra) {
try {
if (!listOfUsers[socket.userid]) return;
listOfUsers[socket.userid].extra = extra;
for (var user in listOfUsers[socket.userid].connectedWith) {
listOfUsers[user].socket.emit('extra-data-updated', socket.userid, extra);
}
} catch (e) {}
});
socket.on('become-a-public-moderator', function() {
try {
if (!listOfUsers[socket.userid]) return;
listOfUsers[socket.userid].isPublic = true;
} catch (e) {}
});
socket.on('get-public-moderators', function(userIdStartsWith, callback) {
try {
userIdStartsWith = userIdStartsWith || '';
var allPublicModerators = [];
for (var moderatorId in listOfUsers) {
if (listOfUsers[moderatorId].isPublic && moderatorId.indexOf(userIdStartsWith) === 0 && moderatorId !== socket.userid) {
var moderator = listOfUsers[moderatorId];
allPublicModerators.push({
userid: moderatorId,
extra: moderator.extra
});
}
}
callback(allPublicModerators);
} catch (e) {}
});
socket.on('changed-uuid', function(newUserId) {
try {
if (listOfUsers[socket.userid] && listOfUsers[socket.userid].socket.id == socket.userid) {
if (newUserId === socket.userid) return;
var oldUserId = socket.userid;
listOfUsers[newUserId] = listOfUsers[oldUserId];
listOfUsers[newUserId].socket.userid = socket.userid = newUserId;
delete listOfUsers[oldUserId];
return;
}
socket.userid = newUserId;
listOfUsers[socket.userid] = {
socket: socket,
connectedWith: {},
isPublic: false,
extra: {}
};
} catch (e) {}
});
socket.on('set-password', function(password) {
try {
if (listOfUsers[socket.userid]) {
listOfUsers[socket.userid].password = password;
}
} catch (e) {}
});
socket.on('disconnect-with', function(remoteUserId, callback) {
try {
if (listOfUsers[socket.userid] && listOfUsers[socket.userid].connectedWith[remoteUserId]) {
delete listOfUsers[socket.userid].connectedWith[remoteUserId];
socket.emit('user-disconnected', remoteUserId);
}
if (!listOfUsers[remoteUserId]) return callback();
if (listOfUsers[remoteUserId].connectedWith[socket.userid]) {
delete listOfUsers[remoteUserId].connectedWith[socket.userid];
listOfUsers[remoteUserId].socket.emit('user-disconnected', socket.userid);
}
callback();
} catch (e) {}
});
function onMessageCallback(message) {
try {
if (!listOfUsers[message.sender]) {
socket.emit('user-not-found', message.sender);
return;
}
if (!listOfUsers[message.sender].connectedWith[message.remoteUserId] && !!listOfUsers[message.remoteUserId]) {
listOfUsers[message.sender].connectedWith[message.remoteUserId] = listOfUsers[message.remoteUserId].socket;
listOfUsers[message.sender].socket.emit('user-connected', message.remoteUserId);
if (!listOfUsers[message.remoteUserId]) {
listOfUsers[message.remoteUserId] = {
socket: null,
connectedWith: {},
isPublic: false,
extra: {}
};
}
listOfUsers[message.remoteUserId].connectedWith[message.sender] = socket;
if (listOfUsers[message.remoteUserId].socket) {
listOfUsers[message.remoteUserId].socket.emit('user-connected', message.sender);
}
}
if (listOfUsers[message.sender].connectedWith[message.remoteUserId] && listOfUsers[socket.userid]) {
message.extra = listOfUsers[socket.userid].extra;
listOfUsers[message.sender].connectedWith[message.remoteUserId].emit(socketMessageEvent, message);
}
} catch (e) {}
}
var numberOfPasswordTries = 0;
socket.on(socketMessageEvent, function(message, callback) {
if (message.remoteUserId && message.remoteUserId === socket.userid) {
// remoteUserId MUST be unique
return;
}
try {
if (message.remoteUserId && message.remoteUserId != 'system' && message.message.newParticipationRequest) {
if (listOfUsers[message.remoteUserId] && listOfUsers[message.remoteUserId].password) {
if (numberOfPasswordTries > 3) {
socket.emit('password-max-tries-over', message.remoteUserId);
return;
}
if (!message.password) {
numberOfPasswordTries++;
socket.emit('join-with-password', message.remoteUserId);
return;
}
if (message.password != listOfUsers[message.remoteUserId].password) {
numberOfPasswordTries++;
socket.emit('invalid-password', message.remoteUserId, message.password);
return;
}
}
}
if (message.message.shiftedModerationControl) {
if (!message.message.firedOnLeave) {
onMessageCallback(message);
return;
}
shiftedModerationControls[message.sender] = message;
return;
}
if (message.remoteUserId == 'system') {
if (message.message.detectPresence) {
if (message.message.userid === socket.userid) {
callback(false, socket.userid);
return;
}
callback(!!listOfUsers[message.message.userid], message.message.userid);
return;
}
}
if (!listOfUsers[message.sender]) {
listOfUsers[message.sender] = {
socket: socket,
connectedWith: {},
isPublic: false,
extra: {}
};
}
// if someone tries to join a person who is absent
if (message.message.newParticipationRequest) {
var waitFor = 120; // 2 minutes
var invokedTimes = 0;
(function repeater() {
invokedTimes++;
if (invokedTimes > waitFor) {
socket.emit('user-not-found', message.remoteUserId);
return;
}
if (listOfUsers[message.remoteUserId] && listOfUsers[message.remoteUserId].socket) {
onMessageCallback(message);
return;
}
setTimeout(repeater, 1000);
})();
return;
}
onMessageCallback(message);
} catch (e) {}
});
socket.on('disconnect', function() {
try {
var message = shiftedModerationControls[socket.userid];
if (message) {
delete shiftedModerationControls[message.userid];
onMessageCallback(message);
}
} catch (e) {}
try {
// inform all connected users
if (listOfUsers[socket.userid]) {
for (var s in listOfUsers[socket.userid].connectedWith) {
listOfUsers[socket.userid].connectedWith[s].emit('user-disconnected', socket.userid);
if (listOfUsers[s] && listOfUsers[s].connectedWith[socket.userid]) {
delete listOfUsers[s].connectedWith[socket.userid];
listOfUsers[s].socket.emit('user-disconnected', socket.userid);
}
}
}
} catch (e) {}
delete listOfUsers[socket.userid];
});
if (socketCallback) {
socketCallback(socket);
}
});
};
Anybody knows whats the fix?
You can either try Ahmed's solution i.e. passing server object here:
require('./Signaling-Server.js') (server);
In your codes, the server object is using http.
I'll suggest trying this instead:
var fs = require('fs');
var options = {
key: fs.readFileSync('fake-keys/privatekey.pem'),
cert: fs.readFileSync('fake-keys/certificate.pem')
};
var express = require("express"),
http = require("https"), // Use HTTPs here -------------
app = express(),
server = http.createServer(options, app);
require('./Signaling-Server.js')(server);
You can either try valid SSL certificate keys or fake-keys.
Here is how to use valid certificates:
var options = {
key: fs.readFileSync('../ssl/private/domain.com.key'),
cert: fs.readFileSync('../ssl/certs/domain.com.crt'),
ca: fs.readFileSync('../ssl/certs/domain.com.cabundle')
};
In Express 3, you should pass the app object to socket.io not the server like in Express 2. Assuming you are using Express 3 and not 2. You just need to change one line to set up socket.io correctly
Try replacing this
require('./Signaling-Server.js')(server);
with this
require('./Signaling-Server.js')(app);

handling session variables inside http.request in express

Hi. When i print the req.session.mySessValue in UI , the value is empty. I think the assigning of req.session.mySessValue = dt.myValue; (express-session) is not proper. could anyone help me on this. Thanks in advance.my express code is
router.get('/', function(req, res, next) {
if(!req.xx) {
return res.redirect('/firstView');
}
var options = {
.......
};
var call = http.request(options, function(resp) {
resp.on('data', function(dt) {
var jsondata = JSON.parse(dt);
req.session.mySessValue = dt.myValue;
});
});
call.end();
call.on('error', function(e) {
console.log("error" +e.message)
});
var v = {
title: 'sample',
req : req
}
res.render('myview', v);
});

Resources