Petrov
Petrov

Reputation: 4250

express.js : naive technical inquiry

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 ?

Upvotes: 1

Views: 73

Answers (1)

thefourtheye
thefourtheye

Reputation: 239443

$ 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

Upvotes: 1

Related Questions