2017-03-03 61 views
0

爲什麼當我導航到/正在搜索時,我的Express node.js應用程序不會加載?我在正確的端口,所以我感到困惑,爲什麼不加載;它會給出404錯誤消息。我突出了下面有問題的部分。爲什麼我的路由不能加載node.js?

var app = express(); 

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

// uncomment after placing your favicon in /public 
//app.use(favicon(path.join(__dirname, 'public', 'favicon.ico'))); 
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('/users', users); 

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

app.get('/', function(req, res) {res.render('index')}); 
**app.get('/searching', function(req, res){ 
res.send("WHEEE"); 
});** 

    // 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; 
app.listen(8020); 

回答

0

this Express FAQ,你需要把你的404處理器在最底層,其它所有功能都執行之後。

所以,只需像下面這樣移動你的功能即可。

var app = express(); 

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

// uncomment after placing your favicon in /public 
//app.use(favicon(path.join(__dirname, 'public', 'favicon.ico'))); 
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('/users', users); 



app.get('/', function(req, res) { 
    res.render('index') 
}); * * app.get('/searching', function(req, res) { 
    res.send("WHEEE"); 
}); * * 

// 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'); 
}); 

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

module.exports = app; 
app.listen(8020); 
相關問題