问题描述
我正在尝试将Express应用程序迁移到hapi.js,但是我的路由遇到了麻烦.我只想要2 GET:我的索引"/",以及所有非"/"的东西都重定向到"/".
I'm trying to migrate my Express app to hapi.js, and I having trouble with my routes. I just want 2 GET : my index '/', and everything that is not '/' to redirect to '/'.
使用Express我有这个:
Using Express I had this:
// 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('/');
});
我在hapi.js上遇到问题,无法获得相同的行为.我的静态道路"看起来像这样:
I have issues with hapi.js to get the same behaviour. My "static road" looks like this:
server.route({
method: 'GET',
path: '/{path*}',
handler: {
directory: {
path: 'public',
listing: false
}
}
});
我的"404之路"将是:
and my "404 road" would be:
server.route({
method: 'GET',
path: '/{path*}',
handler: function (request, reply) {
reply.redirect('/');
}
});
我得到这个错误:
Error: New route /{path*} conflicts with existing /{path*}
我该如何解决?
推荐答案
您要使用相同的方法和路径定义2条路由,就hapi的路由器而言,这是一个冲突.这就是为什么您会收到错误消息.
You're defining 2 routes with the same method and path, which is a conflict as far as hapi's router is concerned. That's why you're getting the error.
如果directory
处理程序未找到文件,则默认情况下它将以404错误响应.
If a file isn't found by the directory
handler, it will respond with a 404 error by default.
您可以做的是使用onPreReponse
处理程序拦截该处理程序,该处理程序检查响应是否为错误响应( Boom 对象),如果是这样,则可以根据需要进行响应.在您的情况下,请重定向到/
:
What you can do is intercept this with an onPreReponse
handler, which checks if the response is an error response (a Boom object), and if so respond however you wish. In your case by redirecting to /
:
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');
});
推荐阅读:
- hapi的请求生命周期和扩展点: http://hapijs.com/api#request-lifecycle
- 响应对象: http://hapijs.com/api#response-object
- hapi's request lifecycle and extension points: http://hapijs.com/api#request-lifecycle
- The response object: http://hapijs.com/api#response-object
这篇关于hapi.js-404路由VS静态文件路由的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!