當app.listen()與app.get()在同一個文件中時,它可以工作;當我通過require在其他文件中添加app.get()調用時,它們不起作用:爲什麼Express.js的app.get()只能在同一個文件中調用app.listen()被調用?
// ~ means root folder
// This below is in ~/index.js
var routes = require('~/routes/routes.js');
var server = app.listen(3000, function() {
console.log('Listening on port %d', server.address().port);
});
app.get('/snails', function (req, res) {
res.send('ESCARGOT');
});
// This below is in ~/routes/routes.js
var app = module.exports = require('exports')();
app.get('/birds', function() {
res.send('PENGUIN');
});
// SUCCESS -> localhost:3000/snails will return "ESCARGOT"
// FAIL -> localhost:3000/birds will return "Cannot GET /birds"
第二個證明點的例子;這次,app.listen()被移動到routes.js:
// ~ means root folder
// The below is in ~/index.js
var routes = require('~/routes/routes.js');
app.get('/snails', function (req, res) {
res.send('ESCARGOT');
});
// The below is in ~/routes/routes.js
var app = module.exports = require('exports')();
app.get('/birds', function() {
res.send('PENGUIN');
});
var server = app.listen(3000, function() {
console.log('Listening on port %d', server.address().port);
});
// FAIL -> localhost:3000/snails will return "Cannot GET /snails"
// SUCCESS -> localhost:3000/birds will return "PENGUIN"
這是爲什麼?是否因爲app.listen()只針對調用它的文件?
你是否包含'routes/routes.js'?它有權訪問「應用程序」嗎? – 2014-10-07 17:58:36
編輯上面的代碼以包含它們 – geoyws 2014-10-07 17:59:21
我不確定爲什麼這樣會起作用,因爲您不會將'res'添加爲路由回調參數之一。 – 2014-10-07 18:00:44