Using inert plugin I tried to add the public folder where I kept my css, js files. But on my views folder I can't access them. I'm using handlebars. Even if I keep only the style.css on the views folder still html can't access that style file.
This is my folder structure:
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')
});
}
I tried to add relative path also on the server like this :
const server = hapi.server({
port: Number(process.argv[2] || 3000),
routes: {
files: {
relativeTo: Path.join(__dirname, 'public')
}
}
});
But in vain.
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;
}
You have to define a route to serve the content of your public folder.
This can be done with the 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')
}
}
})
}
This will create a route that will serve any content in the public
directory, so your css will be accessible via http://localhost:3000/public/css/style.css .
This mean you don't have to access the stylesheet with a relative path and can use an absolute path in your home.html :
<link rel="stylesheet" href="/public/css/style.css" />
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.