gpt4 book ai didi

node.js - hapi.js - 404 路由 VS 静态文件路由

转载 作者:IT老高 更新时间:2023-10-28 23:16:13 27 4
gpt4 key购买 nike

我正在尝试将我的 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('/');
});

我在使用 hapi.js 时遇到了问题,无法获得相同的行为。我的“静态道路”是这样的:

server.route({
method: 'GET',
path: '/{path*}',
handler: {
directory: {
path: 'public',
listing: false
}
}
});

而我的“404 路”将是:

server.route({ 
method: 'GET',
path: '/{path*}',
handler: function (request, reply) {
reply.redirect('/');
}
});

我得到这个错误:

Error: New route /{path*} conflicts with existing /{path*}

我该如何解决这个问题?

最佳答案

您使用相同的方法和路径定义了 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');
});

推荐阅读:

关于node.js - hapi.js - 404 路由 VS 静态文件路由,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29305065/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com