我正在尝试在NodeJS中创建两个单独的路由,我在客户端使用快速框架和角度。我目前能够通过访问localhost:3000/
成功呈现我的索引页面,但是当我尝试通过访问localhost:3000/login
呈现登录页面时,我收到GET /login 404
错误并且不确定为什么b / c我把它设置得非常类似于索引路径。不确定我是否错过了什么。
这是我的app.js
//require dependencies
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');
//require routes but do not user yet
var routes = require('./routes/index');
var login = require('./routes/login');
//start app
var app = express();
// view engine setup - default views directory
app.set('views', path.join(__dirname, 'views'));
app.locals.delimiters = '<% %>';
app.set('view engine', 'hjs'); //use hogan templating for views
// uncomment after placing your favicon in /public
//app.use(favicon(__dirname + '/public/favicon.ico'));
app.use(logger('dev'));
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: false }));
app.use(cookieParser());
app.use(require('less-middleware')(path.join(__dirname, 'public')));
app.use(express.static(path.join(__dirname, 'public')));
app.use('/', routes);
app.use('/login', login);
// 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 handlers
// development error handler
// will print stacktrace
if (app.get('env') === 'development') {
app.use(function(err, req, res, next) {
res.status(err.status || 500);
res.render('error', {
message: err.message,
error: err
});
});
}
// production error handler
// no stacktraces leaked to user
app.use(function(err, req, res, next) {
res.status(err.status || 500);
res.render('error', {
message: err.message,
error: {}
});
});
module.exports = app;
路由/ login.js
var express = require('express');
var router = express.Router();
router.get('/login', function(req, res){
res.render('login');
});
module.exports = router;
视图/ login.hjs
<!DOCTYPE html>
<html>
<head>
</head>
<body>
HELLO WORLD
</body>
</html>
访问localhost:3000 / login呈现以下内容:
{{ message }}
{{ error.status }}
{{ error.stack }}
答案 0 :(得分:8)
撰写app.use('/login', login)
时,您告诉Express在名称空间下使用您的路由器:'/ login';因此,定义到 login.js 的所有路由都不需要此前缀。
尝试访问localhost:3000/login/login
;)
然后,只需将您的路由器更改为:
router.get('/', function(req, res){
res.render('login');
});