1

我在了解 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]));

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

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

4

1 回答 1

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

于 2013-08-25T03:03:21.450 回答