1

I'm having some trouble getting my head around express.js routes

If I set up the out-of-the-box hello world app i get a basic setup with a single route

app.get('/', routes.home);

As in the express.js docs, in app.routes my single route has an object like this :

{ path: '/',
method: 'get',
callbacks: [Object],
keys: [],
regexp: /^\/\/?$/i }

but if i console.log into the object

console.log(app.routes.get[0].callbacks[0]);

I get "[Function]" and if I do

console.log(JSON.stringify(app.routes.get[0].callbacks[0]));

I get "undefined" since the callback is a function...

What is going on here, technically ? How can I have a look at the callback I've defined for my route ?

Petrov
  • 4,200
  • 6
  • 40
  • 61
  • This is in fact a repeat of [this SO question][1] from last year... [1]: http://stackoverflow.com/a/9460876/1094784 – Petrov Aug 25 '13 at 10:01
  • possible duplicate of [console.log javascript \[Function\]](http://stackoverflow.com/questions/9460826/console-log-javascript-function) – WiredPrairie Aug 25 '13 at 15:48

1 Answers1

1
$ node server.js 
{ get: 
   [ { path: '/',
       method: 'get',
       callbacks: [Object],
       keys: [],
       regexp: /^\/\/?$/i },
     { path: '/hello.txt',
       method: 'get',
       callbacks: [Object],
       keys: [],
       regexp: /^\/hello\.txt\/?$/i } ] }

[Function]

undefined

Code

var express = require('express');
var app = express();
app.get('/', function(req, res){
      res.send('Hello World');
});
app.get('/hello.txt', function(req, res){
      res.send('Hello World');
});
console.log(app.routes);
console.log(app.routes.get[0].callbacks[0]);
console.log(JSON.stringify(app.routes.get[0].callbacks[0]));

Callbacks[0] has a function, not a JSON object. Thats why JSON.stringify returns undefined

thefourtheye
  • 233,700
  • 52
  • 457
  • 497
  • thanks @thefourtheye for your answer, but it's not really what i needed - cf the same SO question below with correct answer – Petrov Aug 25 '13 at 10:00
  • @Petrov Your original question was little different. That's okay. Have a good day :) – thefourtheye Aug 25 '13 at 10:15