I am new to express. Basically my question is very simple. I want to serve files like /css javascript from one public directory..
layout.hbs
<html>
<head>
<link href="css/style.css" rel="stylesheet" />
<script src="js/app.js"></script>
</head>
<body>
{{{body}}}
</body>
</html>
router.js --> I have three route that point to one index.hbs
router.get("/", function(req,res){
res.render("index.hbs");
})
router.get("/articles", function(req,res){
res.render("index.hbs");
})
router.get("/articles/show/:id", function(req,res){
res.render("index.hbs");
})
Now the problem is when I run this address:
curl "http://localhost:3000/"
http://localhost:3000/js/app
http://localhost:3000/css/style.css
----------------------------------------------
curl "http://localhost:3000/articles"
http://localhost:3000/articles/js/app
http://localhost:3000/articles/css/style.css
----------------------------------------------
curl "http://localhost:3000/show/1"
http://localhost:3000/show/1/js/app
http://localhost:3000/show/1/css/style.css
notice that the /css and /js path keep changing in accordance to UrlRequest. How to prevent this from happening?
I am using express and handlebars, and have already set my static file
app.use(express.static(path.join(__dirname, 'public');
To serve static files such as images, CSS files, and JavaScript files, use the express.static built-in middleware function in Express. The root argument specifies the root directory from which to serve static assets. For more information on the options argument, see express.static.
The main layout is the HTML page wrapper which can be reused for the different views of the app. {{{body}}} is used as a placeholder for where the main content should be rendered.
hbs is a express. js wrapper for the handlebars. js javascript template engine. Handlebars. js is a template engine to make writing html code easier, if intrested you can look here.
You can open and view an HBS file using any text editor. However, if you intend to edit the file, you should open the file using a source code editor, such as NotePad++ or Atom. These applications provide helpful source code editing tools and highlight the file's syntax correctly.
You should specify the URLs to your JS and CSS as absolute URLs in your template: instead of css/style.css
, use /css/style.css
.
The first means "use this path relative to this page to browsers (and curl), the second "use this path relative to the host - which is what you want.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With