hapijs - 从具有可变路径名的目录处理程序提供静态文件
hapijs - serve static files from directory handler with variable path name
我正在尝试使用 hapijs + inert plugin
在我的路由文件中做这样的事情
{
method: 'GET',
path: '/l/{path*}',
handler: {
directory: {
path: (req) => {
const defaultDir = '/public';
return getHostInfo(req.headers.host).then((d) => {
if (!d || !d.directory) return defaultDir;
return d.directory;
}).catch((e) => {
return defaultDir;
});
}
}
}
},
path
参数需要一个字符串、数组或函数,其中 returns 一个字符串或数组……在我的例子中,我的函数 returns 一个承诺……所以它没有工作。
我尝试添加 hapi-as-promised
包来修改 reply
函数以支持 then
方法,但没有用。
基本上我想根据主机 header 值从一个目录或另一个目录提供静态资产。
好吧,我唯一想到的就是这个 hack。首先,你必须做一个扩展点来制作你的异步内容:
server.ext({
type: `onPreHandler`,
method: (request, reply) => {
const defaultDir = '/public';
return getHostInfo(request.headers.host).then((d) => {
if (!d || !d.directory) {
request.app.dirPath = defaultDir;
return;
}
request.app.dirPath = d.directory;
}).catch((e) => {
request.app.dirPath = defaultDir;
}).then(() => {
return reply.continue();
});
}
});
然后是路线:
{
method: `get`,
path: `/l/{path*}`,
handler: {
directory: {
path: (request) => {
return request.app.dirPath;
}
}
}
}
我不知道这种方式是否正确,但我测试过并且有效。所以我希望这会有所帮助。而且我要注意,出于某种原因,在生产环境中使用节点到服务器文件并不是一种常见的方式。
我正在尝试使用 hapijs + inert plugin
在我的路由文件中做这样的事情{
method: 'GET',
path: '/l/{path*}',
handler: {
directory: {
path: (req) => {
const defaultDir = '/public';
return getHostInfo(req.headers.host).then((d) => {
if (!d || !d.directory) return defaultDir;
return d.directory;
}).catch((e) => {
return defaultDir;
});
}
}
}
},
path
参数需要一个字符串、数组或函数,其中 returns 一个字符串或数组……在我的例子中,我的函数 returns 一个承诺……所以它没有工作。
我尝试添加 hapi-as-promised
包来修改 reply
函数以支持 then
方法,但没有用。
基本上我想根据主机 header 值从一个目录或另一个目录提供静态资产。
好吧,我唯一想到的就是这个 hack。首先,你必须做一个扩展点来制作你的异步内容:
server.ext({
type: `onPreHandler`,
method: (request, reply) => {
const defaultDir = '/public';
return getHostInfo(request.headers.host).then((d) => {
if (!d || !d.directory) {
request.app.dirPath = defaultDir;
return;
}
request.app.dirPath = d.directory;
}).catch((e) => {
request.app.dirPath = defaultDir;
}).then(() => {
return reply.continue();
});
}
});
然后是路线:
{
method: `get`,
path: `/l/{path*}`,
handler: {
directory: {
path: (request) => {
return request.app.dirPath;
}
}
}
}
我不知道这种方式是否正确,但我测试过并且有效。所以我希望这会有所帮助。而且我要注意,出于某种原因,在生产环境中使用节点到服务器文件并不是一种常见的方式。