【问题标题】:express.js : naive technical inquiryexpress.js : 天真的技术查询
【发布时间】:2013-08-25 02:48:52
【问题描述】:

我很难理解 express.js 路由

如果我设置了开箱即用的 hello world 应用程序,我将获得一个具有单一路线的基本设置

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

就像在 express.js 文档中一样,在 app.routes 我的单个路由有一个像这样的对象:

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

但如果我 console.log 进入对象

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

我得到“[Function]”,如果我得到了

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

我得到“未定义”,因为回调是一个函数......

从技术上讲,这里发生了什么?如何查看我为路由定义的回调?

【问题讨论】:

标签: node.js express


【解决方案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

代码

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] 有一个函数,而不是 JSON 对象。这就是为什么JSON.stringify 返回undefined

【讨论】:

  • 感谢@thefourtheye 的回答,但这并不是我真正需要的 - 请参阅下面的相同 SO 问题并提供正确答案
  • @Petrov 您最初的问题略有不同。没关系。祝你有美好的一天:)