2017-08-12 205 views
0

我剛剛生成了Express應用並添加了自定義路由(/ configuration)。但是,如果我嘗試打開http://localhost:3000/configuration,服務器將返回404 Not Found錯誤。我檢查了代碼,不明白錯誤在哪裏。爲什麼在Express/node.js中的路由器返回404

app.js

var express = require('express'); 
var path = require('path'); 
var favicon = require('serve-favicon'); 
var logger = require('morgan'); 
var cookieParser = require('cookie-parser'); 
var bodyParser = require('body-parser'); 

var index = require('./routes/index'); 
var config_page = require('./routes/configuration'); 

var app = express(); 

// view engine setup 
app.set('views', path.join(__dirname, 'views')); 
app.set('view engine', 'pug'); 

app.use(logger('dev')); 
app.use(bodyParser.json()); 
app.use(bodyParser.urlencoded({ extended: false })); 
app.use(cookieParser()); 
app.use(express.static(path.join(__dirname, 'public'))); 

app.use('/', index); 
app.use('/configuration', config_page); 

// catch 404 and forward to error handler 
app.use(function(req, res, next) { 
    var err = new Error('Not Found'); 
    err.status = 404; 
    next(err); 
}); 

// error handler 
app.use(function(err, req, res, next) { 
    // set locals, only providing error in development 
    res.locals.message = err.message; 
    res.locals.error = req.app.get('env') === 'development' ? err : {}; 

    // render the error page 
    res.status(err.status || 500); 
    res.render('error'); 
}); 

module.exports = app; 

路由/ configuration.js(路由/ index.js是相似的)

var express = require('express'); 
var router = express.Router(); 

/* GET configuration page. */ 
router.get('/configuration', function(req, res, next) { 
    res.render('configuration', { title: 'My App | Configuration' }); 
}); 

module.exports = router; 

回答

2

此代碼是問題

// catch 404 and forward to error handler 
app.use(function(req, res, next) { 
    var err = new Error('Not Found'); 
    err.status = 404; 
    next(err); 
}); 

也是生成的當前Url你的申請是http://localhost:3000/configuration/configuration。如果你對此進行查詢,那麼它將起作用。現在,如果你想與http://localhost:3000/configuration一起使用它。那麼你需要從任何地方移除路徑。可能是你可以在這樣的主文件中更改

app.use(logger('dev')); 
app.use(bodyParser.json()); 
app.use(bodyParser.urlencoded({ extended: false })); 
app.use(cookieParser()); 
app.use(express.static(path.join(__dirname, 'public'))); 

app.use('/', index); 
app.use('/',config_page); //-----------> this is the line you need to change 

它如何用於錯誤處理。刪除它並添加此代碼以捕獲應用程序中的任何錯誤。

process.on('uncaughtException', function (err) { 
    // This should not happen 
    logger.error("Pheew ....! Something unexpected happened. This should be handled more gracefully. I am sorry. The culprit is: ", err); 
}); 
+0

現在它返回'無法GET /配置' – mxsin

+0

我相信「無法GET/xyz」消息是默認的404消息。也不知道這個答案如何改變任何事情,只要錯誤處理結束,它不應該干涉。我很確定404錯誤不算作未捕獲的異常 – Poootaatoooo

+0

我剛剛注意到,如果您將所有路由存儲在一個文件中(例如index.js),那麼一切正常。但是,如果爲每個頁面在**路由**中創建一個單獨的**。js **,則服務器開始爲除主頁面之外的所有頁面返回404錯誤。我無法理解Express中路由器的邏輯... – mxsin