Rectangle 27 12

You may have also put your console.log after an expectation that fails and is uncaught, so your log line never gets executed.

Yep, that was my issue, thanks for suggesting this. I moved the console logs to BEFORE the failing .expect, and they show now.

node.js - Testing javascript with Mocha - how can I use console.log to...

javascript node.js mocha
Rectangle 27 9

Okay, after doing some research I've found out that opening ports in Heroku is disabled and not allowed.

The only way around this is to use sub-domains and then in-app to use a proxy module (like subdomain-router which I use).

BUT - Heroku don't let you create sub-domains on their domain, meaning that is fixed and cannot have sub-domains. In Heroku manuals, they demand you to have your own domain and dns provider to do such thing, by creating an A-alias (CNAME) in the dns table in your domain settings, that will refer to your app herokuapp domain, and then using the command heroku domains:add to add your domain to the allowed origin list.

You can read more here. It provides all the info you need.

Yeah you'll only have that one port, but you can serve your websockets through there as well as HTTP requests.

Heroku + node.js: I have a server which uses multiple ports. How can I...

node.js heroku deployment port subdomain
Rectangle 27 0

    .then(function(request) {
TypeError: Cannot call method 'then' of undefined
    at Object.<anonymous> (/tmp/test.js:37:6)
    at Module._compile (module.js:456:26)
    at Object.Module._extensions..js (module.js:474:10)
    at Module.load (module.js:356:32)
    at Function.Module._load (module.js:312:12)
    at Function.Module.runMain (module.js:497:10)
    at startup (node.js:119:16)
    at node.js:902:3

Then I add return deffered.promise; in the end of requestTo, getResult and getData functions and this works well. So, do not miss any return and it will be ok.

node.js - How can I use Q-lib with restify in Nodejs - Stack Overflow

node.js asynchronous q restify
Rectangle 27 0

I was able to resolve my issue by adding a regex that excluded my /proxy route to where bodyParser.json was being added within express.js. I found that from this answer

node.js - How can I use "express-http-proxy" after bodyParser.json() h...

node.js express proxy meanjs
Rectangle 27 0

I know it's a little late to help @Grimtech but I'll leave my opinion for other people that arrives here eventually:

First of all I rather to model @Grimtech's problem differently. Something like this:

client.hmset("user:chris", "weapon", "some weapon", "race", "some race", "potion", "some potion");
client.hmset("user:pete", "weapon", "same weapon", "race", "other race", "potion", "other potion");

Then I would have a method in Node returning a json like the following, assuming that I can have more than one key starting with "user:chris":

router.get('/users/:user_id', function(req, res, next) {
    var response = [];
    var client = redis.createClient();
    client.keys("user:" + req.params.user_id + "*", function (err, users) {
        users.forEach(function (key, pos) {
            client.hgetall(key, function (err, user) {
                if (pos === users.length - 1) {

The json returned will have all the "user:chris" attributes so yo can do whatever you want in the client browser.

node.js - How can I use arr.forEach to call async JavaScript redis cal...

javascript node.js asynchronous redis
Rectangle 27 0

After switching to for a while I ran into a few problems due to the asynchronous nature of the module when loading the session information. So I ended up creating my own module called It is used like this:

var express = require('express');
var app = express();
var server = require('http').createServer(app);

//Setup cookie and session handlers
//Note: for sessionStore you can use any sessionStore module that has the .load() function
//but I personally use the module 'sessionstore' to handle my sessionStores.
var cookieParser = express.cookieParser('secret');
var sessionStore = require('sessionstore').createSessionStore();

  app.set('port', process.env.PORT || 3000);
  //make sure to use the same secret as you specified in your cookieParser
  app.use(express.session({secret: 'secret', store: sessionStore}));

app.get('/', function(req, res){
  res.send('<script src="/"></script><script>io.connect();</script>Connected');

server.listen(app.get('port'), function(){
  console.log('Listening on port ' + app.get('port'));

var io = require('').listen(server);

  //use to get our session data
  io.set('authorization', require('')(cookieParser, sessionStore));

io.on('connection', function(socket){
  //we now have access to our session data like so
  var session = socket.handshake.session;

node.js - Since connect doesn't use the parseCookie method anymore, ho...

node.js session authentication express
Rectangle 27 0

Just to be more clear about what it takes to get this working (because I still struggled for a while after finding this answer!), here are the steps I took:

As described above, in $APP_HOME/server/middleware.json, add the body-parser to the "parse" section:

  "initial:before": {
    "loopback#favicon": {}
  "initial": {
    "compression": {},
    "cors": {
      "params": {
        "origin": true,
        "credentials": true,
        "maxAge": 86400
  "session": {
  "auth": {
  "parse": {
    "body-parser#json": {},
    "body-parser#urlencoded": {"params": { "extended": true }}
  "routes": {
  "files": {
  "final": {
    "loopback#urlNotFound": {}
  "final:after": {
    "errorhandler": {}
var loopback = require('loopback');
var bodyParser = require('body-parser');
var multer = require('multer');

var boot = require('loopback-boot');

var app = module.exports = loopback();

app.use(bodyParser.json()); // for parsing application/json
app.use(bodyParser.urlencoded({ extended: true })); // for parsing application/x-www-form-urlencoded
app.use(multer()); // for parsing multipart/form-data

app.start = function() {

Then, since I didn't want to mess with custom routes, I added the following to $APP_HOME/common/models/model.js:

module.exports = function(Model) {

  Model.incoming = function(req, cb) {
    cb(null, 'Hey there, ' + req.body.sender);
    { accepts: [
      { arg: 'req', type: 'object', http: function(ctx) {
        return ctx.req;
    returns: {arg: 'summary', type: 'string'}

I can now run my app with $> slc run .

When I post to the endpoint, it now gets parsed properly, and all is well with the world. I hope this helps someone else!

You sir, are a legend.

node.js - How can I use body-parser with LoopBack? - Stack Overflow

node.js express middleware loopbackjs body-parser
Rectangle 27 0

First off I think it is important to understand that an Express app in nothing more than an initiated Express app object which is listening on some port (see ex1). On the first line of this example you can see what is called a linux hashbang or shebang which is a line that tells your shell what kind of interpreter it should use to execute the following file. Therefore it is possible to create a file with the node hashbang, remove the .js extension en still be able to execute it using ./{myscript} where ./ causes it to run.

Now that we got the basics down I am fairly certain you used the express-generator to create your app. Which indeed tells you to run your app using the DEBUG=node:* ./bin/www. The ./bin/www/ simply runs the www file in the /bin folder. Which is essentially a javascript file with a node hashbang that imports the app instance from app.js and initiates and http server on it, which start listening for events. The DEBUG={name}:* command is used by npm debug npm debug link. It simply tells the package which debug functions it should use. The * being a wildcard for: use all of them all (see npm debug package docs for for info).

#!/usr/bin/env node
var express = require('express')
var app = express()

app.get(function(req, res) {

app.listen(8080, function(){
    console.log('Server started on port:8080')

Tip if you simply dont like typing the command because it's too long I suggest you to add it to the scripts section in your package.json.

'scripts': {
    'start': 'DEBUG=node:* ./bin/www'

You can then run it by using npm start

node.js - How can run app using Express 4 without "DEBUG=node:* ./bin/...

node.js express phpstorm express-4
Rectangle 27 0

I deprecated and removed the less4clients package which extends a express.js server with a less css rendering middleware to render less files to css on the fly (and cache the results in memory) in favor of a newer project of mine called DocPad that lets you use any pre-processor you want.

As of this time of writing, it does not have an easy to use express middleware like less4clients, however such a thing is on the roadmap soon. Instead you can use it standalone or via its API.

In hindsight I should have kept less4clients available and just stated in it's readme that DocPad is the new way of doing things, but I never realised less4clients was actually being used by anyone as DocPad has already gained so much attention.

seems that the package 'less4clients' is removed from your GitHub-account. Can you provide a new link?

node.js - How can I minify CSS using `less` in `express-js`? - Stack O...

css node.js express minify
Rectangle 27 0

            //You need to send a response here.
            //Each request must always get exactly one response no matter
            //how your code logic branches.
            //Otherwise, this request will just hang until timeout, which is bad
            res.send(500, err);
            //also, using early returns instead of a big if/else tree is cleaner IMHO
        }else if(post.password!=user.password){ //TODO figure out hash and salt stuff
            //This should work just fine.
            //In the comments you claim a console.log before and after this print
            //out but this "doesn't work".
            //1. I have good reason to be dubious of your claims here.
            // Clear your mind and double check yourself.
            //2. Get some technical detail beyond "Doesn't work".
            // Use curl and see what happens. Does the request just hang unresponded?
            res.redirect('/lobby'); //<- this doesn't work

I edited my code in the post to show console.log calls and added screenshots of the node.js output as well as the request details shown in the Firefox console. Everything seems to be executed just fine... except that in my browser, the redirect doesn't take place. If I manually enter localhost/lobby into my browser bar, the routing works, and the auth too.

You are doing an ajax XmlHttpRequest. Those don't automatically do redirects like a normal browser page load. You have to manually in browser js change window.location based on the server response's Location header.

Oh okay... Didn't think it made a difference on the server side of things. Thansk!

javascript - In a node.js app using express, how can one call response...

javascript node.js express mongoose
Rectangle 27 0

Closures and try-catch

"Generators" (besides being "generators") are also the basic buildings blocks of "fibers" or "coroutines". With fibers, you can "pause" a function waiting for an async call to return, effectively avoiding to declare a callback function "on the spot" and creating a "closure". Say goodbye to callback hell.

...he said something about call stack and exceptions

The problem with "closures" is that even if they "magically" keep the state of the local variables for the callback, a "closure" can not keep the call stack.

At the moment of callback, normally, the calling function has returned a long time ago, so any "catch" block on the calling function cannot catch exceptions in the async function itself or the callback. This presents a big problem. Because of this, you can not combine callbacks+closures with exception catching.

...and would change the node landscape

If you use generators to build a helper lib like Wait.for-ES6 (I'm the author), you can completely avoid the callback and the closure, and now "catch blocks" work as expected, and the code is straightforward.

It'd be really helpful if you could give a snippet of code to highlight the difference in common scenarios (making an http request or a db call).

Check Wait.for-ES6 examples, to see the same code with callbacks and with fibers based on generators.

javascript - What are ES6 generators and how can I use them in node.js...

javascript node.js generator ecmascript-6
Rectangle 27 0

Since you're iterating over replies, you can check when you've reached the last element and only call callback in that instance.

client.KEYS('user/' + requesteduser + '/*', function(err, replies) {

         replies.forEach(function (reply, i) {
             client.GET(reply, function(err, value) {
                  // get the key name so we can populate a js object
                  var n = reply.lastIndexOf('/');
                  var key = reply.substring(n + 1, reply.length);
                  userstats[key] = value;


                  if (i == replies.length-1) callback(null, userstats); // parent expects (err, userstats)


node.js - How can I use arr.forEach to call async JavaScript redis cal...

javascript node.js asynchronous redis
Rectangle 27 0

After the social login, when the user is redirected to the callback url, you can create your own token, e.g. using uuid, and then send it to the client.

For all the consequent requests the client needs to use that token for authentication and you have to manage its expiration.

How can I add authenticated REST requests for my Node.js App which use...

node.js rest passport.js
Rectangle 27 0

If you can call out shellscript, and you can use Node.js, I'm assuming you could also install and use PhantomJS, which is a headless WebKit port. (I.e. an actual honest to goodness WebKit renderer that just doesn't require a window to work.) This will let you use Javascript and the familiar web libraries to manipulate the document. As an example, the following gets you the width of the logo element towards the upper left Stack Overflow site:

page = require('webpage').create(); // create a new "browser"'', function() {
  // callback when loading completes
  var logoWidth = page.evaluate(function() {
    // This runs in the rendered page and uses the version of jQuery that SO loads.
    return $('#hlogo').width();

  console.log(logoWidth); // prints 250, the same as Chrome.

  phantom.exit(); // for some reason you need to exit manually

The documentation for PhantomJS will tell you more about what you can do with it and how.

One caveat however is that loading a page takes a while, since it needs to fetch CSS and scripts and generally do everything a browser does. I'm not sure if and how PhantomJS does any caching, if it does it might make sense to reuse the same process for multiple scrapes of the same site.

python - How to determine the size of html table in pixels given an ht...

python node.js
Rectangle 27 0

In your request object there is a property called connection, which is a net.Stream object. The net.Stream object has a property remoteAddress, therefore you should be able to get the IP with this call:


See documentation for http and net

As @juand points out in the comments, the correct method to get the remote IP, if the server is behind a proxy, is request.headers['X-Forwarded-For']

This gives me an IP address different from what gives me. Why would that be?

I have my API service installed on a instance. When I try to access it from my computer, I get an IP address of "10.2.XXX.YYY" whereas my real world IP is "67.250.AAA.BBB"


If im not mistaken, node lower-cases the headers so it should be headers['x-forwarded-for']

api - How can I get the user's IP address using Node.js? - Stack Overf...

api node.js ip
Rectangle 27 0

Ok, I turned to sha512_crypt instead and found a nice library for node called sha512crypt-node. The README itself contains an example for both Python and Node, exactly what I needed. Here's a little example for ppl. using these platforms:

from passlib.hash import sha512_crypt

orig = "password"
h = sha512_crypt.encrypt(orig)
print("hash", h)
# h for eg. is $6$rounds=100000$5YnTXatKh4b1pLjp$3QQjVIfjrbiTakj.wkaw1woAcFiPRAjJP2U/b3BiGW4m8OvI8x0tgw1bb63dNQWMUl1uYNDBcTO3tWgrJ6eHh1

okay = sha512_crypt.verify(orig, h)
print("verified", okay)
var sha512crypt = require("sha512crypt-node").sha512crypt;

// origHash is the hash generated by passlib    
var origHash = "$6$rounds=100000$5YnTXatKh4b1pLjp$3QQjVIfjrbiTakj.wkaw1woAcFiPRAjJP2U/b3BiGW4m8OvI8x0tgw1bb63dNQWMUl1uYNDBcTO3tWgrJ6eHh1",
    parts = origHash.split('$'),
    rounds = parts[2],
    salt = '$' + parts[1] + '$' + rounds + '$' + parts[3],
    password = "password";

var hash = sha512crypt(password, salt);
console.log("verified", hash === origHash);

How can I verify a cryptographic hash created by Python's Passlib usin...

python node.js security hash pbkdf2
Rectangle 27 0

By default, a client starts out with http polling and then switches to webSocket after a few polling transactions. As best I've been able to tell, nothing you can do on the server will change the way the client behaves so if you don't support polling on your server and you don't change the way the client is configured, then the initial client connection will not work. But, you can make corresponding changes in BOTH client and server to force to only use webSocket, even from the beginning. If you're looking at the network trace, you will still see an initial HTTP connection because all webSocket connections start with an HTTP connection, but then that HTTP connection is "upgraded" to the webSocket protocol.

You can see all the details on how to configure both client and server to ONLY use webSocket here: 1.x: use WebSockets only?. In a nutshell, you will want to do this in the client for making a connection:

var socket = io({transports: ['websocket'], upgrade: false});

node.js - NodesJS SocketIO - How can I make sure websockets are being ...

node.js websocket
Rectangle 27 0

After hours of frustration, I just added it to middleware.json like so:

"parse": {
    "body-parser#json": {},
    "body-parser#urlencoded": {"params": { "extended": true }}

It is installed as a dependency. Now I have form data in req.body in my routes. My server/boot/routes.js looks like this:

module.exports = function(app) {'/mailing_list', function(req, res) {
        res.send({"status": 1, "message": "Successfully added to mailing list."})

node.js - How can I use body-parser with LoopBack? - Stack Overflow

node.js express middleware loopbackjs body-parser
Rectangle 27 0

Store the SID with the account, when the user logs in during the database validation of the user account call .destroy(sid, fn), then update the SID in the database with the current SID of the user.'/login', function(req, res)
  var sid = req.sessionID;
  var username = req.body.user;
  var password = req.body.pass;

  users.findOne({username : username, password : password}, function(err, result)
    sessionStore.destroy(result.session, function(){
       users.update({_id: result._id}, {$set:{"session" : sid}});

node.js - How can I find the session Id when using express / connect a...

node.js redis express
Rectangle 27 0

The problem is that you pass whole module to use method. In this case can't be called next callback so everything stucks there...


node.js - Nodejs: How can i simply get the request body using express4...

node.js express express-4