我有一个简单的网页,其中定义了/about
,/contact
,/home
和/lessons
路由。除了/lessons
之外,所有路由都可以正常工作。我立即得到一个重定向循环(Error 310 (net::ERR_TOO_MANY_REDIRECTS): There were too many redirects
)。
这是我的主要server.js
代码:
var port = process.env.PORT || 8888;
var app = require('./app').init(port);
var markdown = require('./markdown');
var lessons = require('./lessons.json').lessons;
// app.use(function(req,res,next) {
// console.log('adding lessons to locals');
// res.locals.date = new Date().toLocaleDateString();
// res.locals.lessons = lessons;
// next();
// });
// app.use(app.router);
app.get('/', function (req, res) {
console.log('controller is : home');
res.locals.controller = 'home';
res.render('home');
});
app.get('/:controller', function (req, res, next) {
var controller = req.params.controller;
console.log('controller is : '+ controller);
if (controller == 'about' || controller == 'contact') {
res.locals.controller = controller;
res.render(controller);
} else {
console.log('next was taken!');
next();
}
});
app.get('/lessons', function(req, res) {
res.locals.lessons = lessons;
console.log('controller is : lessons');
res.render('lessons');
});
app.get('/lessons/:lesson', function(req, res) {
console.log('controller is : lesson');
res.locals.controller = 'lessons';
res.send('gimmie the lesson');
});
/* The 404 Route (ALWAYS Keep this as the last route) */
app.get('/*', function (req, res) {
console.log('got 404 request to ' + req.url);
res.render('404');
});
这是用于服务器初始化的
app.js
文件:var express = require('express');
var slashes = require('connect-slashes');
exports.init = function (port) {
var app = express();
app.use(express.static(__dirname + '/public'));
// add middleware to remove trailing slash in urls
app.use(slashes(false));
app.set('views', __dirname + '/views')
app.set('view engine', 'ejs');
app.use(express.bodyParser());
app.use(express.methodOverride());
app.use(express.logger());
app.enable("jsonp callback");
if ('development' == app.get('env')) {
app.use(express.errorHandler({
dumpExceptions: true,
showStack: true
}));
app.use(express.logger({
format: ':method :url'
}));
}
if ('production' == app.get('env')) {
app.use(express.errorHandler());
}
app.use(function (err, req, res, next) {
console.log('Oops, something went wrong');
res.render('500.ejs', {
locals: {
error: err
},
status: 500
});
});
app.listen(port);
console.log("Listening on port %d in %s mode", port, app.settings.env);
return app;
}
我尝试使用
node-inspector
调试应用程序,但是它没有用,因为该应用程序似乎没有进入任何app.get
尝试匹配。当我尝试访问localhost:8888/lessons
时,它立即给我错误编辑:
我想我找到了问题的根源:
/public
目录有一个lessons
文件夹/views
目录具有lessons.ejs
View 例如,当我将
/public/lessons
更改为/public/lessons11
时,问题已解决。有人可以向我解释一下导致重定向循环的原始场景中的表达流程吗?另外,我该怎么办才能解决呢?谢谢
最佳答案
有时候是这样的:
/lessons
; public/lessons
文件夹,并假定这就是预期的目标。因为它是一个文件夹,它将生成一个重定向到/lessons/
(请参见下文); index.html
,并将其交给下一个中间件(connect-slashes
); connect-slashes
中间件删除了结尾的斜杠并发出重定向到/lessons
的命令; 您可以防止静态中间件添加尾部斜杠,这将修复您的重定向循环,我认为:
app.use(express.static(__dirname + '/public', { redirect : false }));