【问题标题】:Adding CSS on hapi.js is not woking在 hapi.js 上添加 CSS 不起作用
【发布时间】:2019-03-17 18:34:41
【问题描述】:

使用 inert 插件我尝试添加我保存 css、js 文件的公共文件夹。但在我的 views 文件夹中,我无法访问它们。我正在使用车把。即使我只保留 views 文件夹中的 style.csshtml 仍然无法访问该样式文件。

这是我的文件夹结构:

app.js
public
   css
     style.css
 views
     home.html
 routes
     user.js

App.js

const server = hapi.server({
   port: Number(process.argv[2] || 3000),
});
const init = async () => {

   await server.register(vision);
   await server.register(inert);
   server.views({
        engines: {
            html: handlebars
        },
        path: path.join(__dirname, 'views'),
        relativeTo: path.join(__dirname, 'public')

    });

}

我尝试在服务器上也像这样添加相对路径:

const server = hapi.server({
   port: Number(process.argv[2] || 3000),
   routes: {
        files: {
            relativeTo: Path.join(__dirname, 'public')
       }
   }
});

但徒劳无功。

Home.html

<html>
<head>
   <title>Login page</title>
   <link rel="stylesheet" href="../css/style.css" />
 </head>
   <body>
        <h2> Welcome </h2>
  </body>
</html>

style.css

body {
background: #456;
font-family: 'Open Sans', sans-serif;
}

【问题讨论】:

    标签: javascript html css node.js hapijs


    【解决方案1】:

    您必须定义一个路由来提供公用文件夹的内容。

    这可以通过Directory Handler来完成:

    const init = async () => {
        await server.register(vision);
        await server.register(inert);
    
        server.views(...)
    
        server.route({
            method: 'GET',
            path: '/public/{param*}',
            handler: {
                directory: {
                    path: path.join(__dirname, 'public')
                }
            }
        })
    }
    

    这将创建一个路由,它将为public 目录中的任何内容提供服务,因此您的 css 将可以通过http://localhost:3000/public/css/style.css 访问。

    这意味着您不必使用相对路径访问样式表,并且可以在 home.html 中使用绝对路径:

    <link rel="stylesheet" href="/public/css/style.css" />
    

    【讨论】:

    • 它成功了,谢谢。但是,如果我不想将此路由保留在 app.js 文件中,而是将其保留在 routes 文件夹中到 user.js 文件中,该怎么办?为此,我是否必须将我的 html 链接更改为href="../public/css/style.css"?我试过了,但没有用。我修改了我的文件夹结构。请看看
    • 提供静态内容的路由大多与您的模板文件没有关系,实际上routes.files.relativeTo 指令仅告诉 hapi 使用您提供的路径,因此在调用h.view 时路由处理程序,路径将从relativeTo 解析,因此它仅在服务器内部有用,而不是来自客户端(例如:视图)。你的 user.js 文件是做什么的?
    • user.js 包含我所有的 server.routes 即return h.view('home') files。我将它们导出以在app.js 上使用。好吧,我把目录路径改成path.join(__dirname, ../'public')
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-10-31
    • 2022-01-21
    相关资源
    最近更新 更多