Serving a static HTML page containing an image using Node JS / Express

I can serve static HTML pages using express. I also set up "ejs" to display a page with data from local variables in my .js file. I just need to display a small logo in the corner of the page along with the rest of the data. Opening only the html file in the browser loads the image just fine, but with the server I get a broken image. I think it might be a problem with my file path or directory structure. Here is my original simple code without vain attempts:


var express = require ('express');
var fs = require ('fs');
var app = express ();
var bodyParser = require ('body-parser');
app.use (bodyParser ());
var server = require ('http').createServer (app);
app.set('views', __dirname + '/views');
app.engine('.html', require('ejs').__express);

var my_name="Goku";
var my_power=9001;

app.get ('/', function (req, res){
    console.log ('GET /');

server.listen (8888);



<input id="name" value=" <%=name%> " /><br>
<input id="power" value=" <%=power%> "/><br>


I have not included the img src line so you can give me the full line, people sometimes miss my subtle syntax errors. By submitting the directory structure, I just have this server.js file in my / home folder and the 'index.html' file in / home / views

Solution suggested by Ploutch: I moved logo.jpg to '/ images' folder which I created under '/ home' section I just added these lines -


app.use(express.static(__dirname + '/images'));



<img src="/logo.jpg" />


Since I am using ejs to render a page with local variables, if I put logo.jpg in the current directory instead of a separate image folder, the image loads fine, but the "name" and "power" output will break.


source to share

1 answer

You need to use your resource files (images, js, css, ...) in a static way.

To do this, put them in a subdirectory, then add this before server.listen

app.use(express.static(__dirname + '/public'));


(Assuming public

is the name of the folder containing your static files)

Then, if your image is named logo.png

, you can call it like this:

<img src="/logo.png" />




All Articles