Thi*_*lon 11 redirect node.js http-status-code-404 hapijs
我正在尝试将我的Express应用程序迁移到hapi.js,并且我的路线出现问题.我只想要2 GET:我的索引'/',以及不是'/'的所有内容都重定向到'/'.
使用Express我有这个:
// static files
app.use(express.static(__dirname + '/public'));
// index route
app.get('/', function (req, res) {
// whatever
}
// everything that is not /
app.get('*', function(req, res) {
res.redirect('/');
});
Run Code Online (Sandbox Code Playgroud)
我有hapi.js的问题,以获得相同的行为.我的"静态路"看起来像这样:
server.route({
method: 'GET',
path: '/{path*}',
handler: {
directory: {
path: 'public',
listing: false
}
}
});
Run Code Online (Sandbox Code Playgroud)
而我的"404道路"将是:
server.route({
method: 'GET',
path: '/{path*}',
handler: function (request, reply) {
reply.redirect('/');
}
});
Run Code Online (Sandbox Code Playgroud)
我收到此错误:
Error: New route /{path*} conflicts with existing /{path*}
Run Code Online (Sandbox Code Playgroud)
我该如何解决这个问题?
Mat*_*son 13
您正在使用相同的方法和路径定义2条路由,就hapi的路由器而言这是一个冲突.这就是你收到错误的原因.
如果directory
处理程序找不到文件,默认情况下它将响应404错误.
您可以做的是使用onPreReponse
处理程序拦截它,该处理程序检查响应是否是错误响应(Boom对象),如果是,则响应您希望的.在您的情况下,通过重定向到/
:
var Hapi = require('hapi');
var server = new Hapi.Server();
server.connection({ port: 4000 });
server.route([{
method: 'GET',
path: '/',
handler: function (request, reply) {
reply('Welcome home!');
}
}, {
method: 'GET',
path: '/{p*}',
handler: {
directory: {
path: 'public',
listing: false
}
}
}
]);
server.ext('onPreResponse', function (request, reply) {
if (request.response.isBoom) {
// Inspect the response here, perhaps see if it's a 404?
return reply.redirect('/');
}
return reply.continue();
});
server.start(function () {
console.log('Started server');
});
Run Code Online (Sandbox Code Playgroud)
推荐阅读:
归档时间: |
|
查看次数: |
3503 次 |
最近记录: |