Saturday, 11 March 2017

req.session is undefined express-session

I know this question has been asked several times. However, none of the answers I've read has solved my question.

Many of them were outdated for express v4, as express-session is currently a separate module. Those question/answers are here:

Other questions are updated, however the solution given doesn't fix my problem. Those question/answers are here:

Most of the solutions are the sequence of middlewares when configuring the app. I've tried different options and I doesn't find the correct way to do it. Maybe it's just that.

In other solution, someone says that session middleware cannot be called, because if it were, req.session would be defined. I've used middlewares just before an after app.use(session({...})), and checked that both get called.

I've also found in this issue someone saying that he gets req.session undefined when the store disconnects. I'm using the default store so far. Could this be the problem?

I'm getting this error:

TypeError: Cannot read property 'destroy' of undefined

It breaks just when I try to logout a session with req.session.destroy() at login.js (see code below)


My code

server.js

const express = require('express');
const session = require('express-session');
const mongo = require('mongodb');
const passport = require('passport');
const path = require('path');
const routes = require('./app/routes');
const login = require('./app/routes/login.js');

const app = express();
app.use(session({
  secret: 'key',
  resave: false,
  saveUninitialized: true,
}));
app.use(passport.initialize());
app.use(passport.session());
app.use('/public', express.static(path.normalize('./public')));
app.use(routes);
app.use(login);
app.set('view engine', 'pug');

const MongoClient = mongo.MongoClient;
MongoClient.connect('mongodb://localhost:27017/myapp')
.then((db) => {
  // Link the database through the app. It will be available in the req.app object
  app.db = db;
  console.log('App listening on port ' + process.env.PORT);
  app.listen(process.env.PORT);
})
.catch((err) => {
  console.log('There was an error connecting to the database.');
  console.log(err);
});

module.exports = app; // For testing

login.js

const express = require('express');
const passport = require('passport');
const router = new express.Router();

// Other login logic here

router.get('/logout', (res, req) => {
  req.session.destroy((err) => {
    req.redirect('/');
  });
});

module.exports = router;



via dgrcode

Promise.all with try/catch simulation

I'm currently running through, and attempting to familiarize myself with promises, and I will cut through the introductory concepts, and get to the meat of the matter. Within NodeJS, using the library BlueBird. I don't want to defer the function calls, I'd also rather not pollute the code more than needed, even though this is introductory coding to get familiar with the premise, as when more advanced concepts are being attempted, I'll get lost on them. I attempted using 'asyn/await' with a try block, but God was that code messy, and didn't work...

Promises contain a catch mechanism built in, which works perfectly, if dealing with a standard single Promise.

// Try/Catch style Promises
funcTwo = function(activate) {
  return new Promise(function(resolve, reject) {
    var tmpFuncTwo;
    if (activate === true) {
      tmpFuncTwo = "I'm successful"
      resolve(tmpFuncTwo)
    } else if (activate === false) {
      tmpFuncTwo = "I'm a failure.";
      reject(tmpFuncTwo)
    } else {
      tmpFuncTwo = "Oh this is not good."
      throw new Error(tmpFuncTwo);
    }
  });
}

funcTwo(true)
  .then(val => {
    console.log("1: ", val)
    return funcTwo()
  })
  .catch(e => {
    console.log("2: Err ", e.message)
  })

The thing that causes me to be somewhat confused is attempting to uphold the same premise with Promise.all, the error is not handled, as the throw pushes directly to the main Controller. The exception that is thrown from this snippet never makes it to the the Catch block.

funcThree = function(val) {
  return new Promise(function(resolve, reject) {
    if (val > 0)
      resolve((val + 1) * 5)
    else if (val < 0)
      reject(val * 2)
    else
      throw new Error("No work for 0");
  })
}
// Output in Dev Console
/* 
  Extrending to the catch block handling, This will fail, the exception is thrown, and ignores the catch block. Terminating the program.
*/
Promise.all([funcThree(1), funcThree(0), funcThree(-3)])
  .then(function(arr) {
    for (var ind = 0; ind < arr.length; ind++) {
      console.log(arr)
    };
  }, function(arr) {
    console.log(arr)
  })
  .catch(function(e) {
    console.log("Error")
  })

I've attempted a simple work around, but I am somewhat new to the language, and am not sure if this is adhering to "Best Practices", as they have been drilled into my mind from Python guidelines.

// Promise all, exceptionHandling
funcThree = (val) => {
  return new Promise(function(resolve, reject) {
    if (val > 0)
      resolve((val + 1) * 5)
    else if (val < 0)
      reject(val * 2)
    else {
      var tmp = new Error("No work for 0");
      tmp.type = 'CustomError';
      reject(tmp);
    }
  })
}

/*
  This works, and doesn't cause any type of mixup
*/
Promise.all([funcThree(1), funcThree(0), funcThree(-3)])
  .then(
    arr => {
      for (var ind = 0; ind < arr.length; ind++) {
        console.log(arr)
      };
    }, rej => {
      if (rej.type == 'CustomError')
        throw rej;
      console.log(arr)
    })
  .catch(e => {
    console.log("Catching Internal ", e.message)
  })

This is using the Native Promise library, as well as bluebird

Is there a way to handle this more natively,



via L.P.

How to limit replies to 1 API Call?

I'm making a Q&A twitter bot w twitter api using direct messages, my problem is each time a user ask a question, after a while, the bot start to response twice the same answers. Is there a way to limit each response to 1 API Call?

here my code:

stream.on('direct_message', function (eventMsg) {
    var msg = eventMsg.direct_message.text;
    var screenName = eventMsg.direct_message.sender.screen_name;
    var msgID = eventMsg.direct_message.id_str;

    if (screenName === ‘MyBotExample) {
        return callbackHandler(msgID);
    }

    else if (msg.search(‘Hi’) !== -1 ) {
        return T.post('direct_messages/new', { 
            screen_name: screenName,
            text: 'Hey, what can I do for you?'} , function () {
            callbackHandler(msgID);
        });
    }

    else {
        return T.post('direct_messages/new', {
            screen_name: screenName,
            text: "I don't know "
        }, function() {
            callbackHandler(msgID);
        });
    }
});

Thanks!



via Isaac

Node.js (nwjs) child_process.spawn returning continuous output

I have a command line application called interface. If I open it up from the terminal, it will sit and wait for input. I type in a json string, and it returns a json string. For example:

JZ:MacOS jcz$ ./interface
{"type":"test"}
{"msg": "Invalid command: test", "type": "error"}

I am trying to launch this process from a nwjs application, so I can send and receive data. What is happening is that the process seems to think I am continuously sending commands to the process when I haven't sent anything at all.

var spawn = require('child_process').spawn;
var py = spawn('./py/dist/interface.app/Contents/MacOS/interface');

py.stdout.on('data', function(data) {
    console.log(data.toString());
});

Without having sent anything at all, if I do py.stdin.end() I get an unending stream:

{"msg": "Could not parse JSON message", "type": "error"}
{"msg": "Could not parse JSON message", "type": "error"}
{"msg": "Could not parse JSON message", "type": "error"}
{"msg": "Could not parse JSON message", "type": "error"}
...

Which is the error message I have programmed in when invalid JSON input is sent.

I would like to be able to send and receive messages to the process using py.stdin.write(string) and have the output appear in the console.



via Jeff