I’m new to JS/Handlebars and I’m unable to display an image from my home.hbs file in VS Code. When I run the server, I get this:
Here’s my server code:
JavaScript
x
17
17
1
const express = require('express');
2
const app = express();
3
const port = 3000;
4
5
6
7
app.set('views', 'views');
8
app.set('view engine', 'hbs');
9
app.use(express.static('public'));
10
11
app.get('/', function(req, res) {
12
res.render('home', {});
13
});
14
15
app.listen(port);
16
console.log('server listening on port 3000');
17
My “home.hbs” code:
JavaScript
1
13
13
1
<!DOCTYPE html>
2
<html>
3
<head>
4
<meta charset="utf-8">
5
<meta name="viewport" content="width=device-width, initial-scale=1">
6
<title>Handlebars at Work</title>
7
</head>
8
<body>
9
<img src="/public/img/logo.png">
10
<h1>Hello There, {{name}}</h1>
11
</body>
12
</html>
13
The “GET” error specifically states
Cannot GET /public/img/logo.png
That’s all the info I have, any help would be much appreciated.
Advertisement
Answer
Specify the path prefix for the static file handler. Change:
JavaScript
1
2
1
app.use(express.static('public'));
2
to
JavaScript
1
2
1
app.use('/public', express.static('public'));
2
and additionally verify that you indeed have a file named public/img/logo.png
.