13

I am new to nodejs. I want to create a very simple website which has 3 pages. In every page I want to display an image to make the pages look uniform.

My code looks like this:

    /**
     * Module dependencies.
     */

    var express = require('express');
    var routes = require('./routes');
    var user = require('./routes/user');
    var http = require('http');
    var path = require('path');
    var fs = require('fs');
    var mail = require("nodemailer").mail;

/*List of variables*/

var app = express();

// all environments
app.set('port', process.env.PORT || 3000);
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'jade');
app.use(express.favicon());
app.use(express.logger('dev'));
app.use(express.json());
app.use(express.urlencoded());
app.use(express.methodOverride());
app.use(app.router);
app.use(express.static(path.join(__dirname, 'public')));

app.get('/main', function(req, res) {

    fs.readFile('./home.html', function(error, content) {
        if (error) {
            res.writeHead(500);
            res.end();
        }
        else {
            res.writeHead(200, { 'Content-Type': 'text/html' });
            res.end(content, 'utf-8');
        }
    });

});

/* After this I have code for post event - all these navigation works perfectly fine*/

in home.html file I have an image to display:

/*Header part of HTML file*/

<body>

        <img class="logo" src="./Heading.png" alt="My_Logo">
        console.log (src);
        <h1 class="center">Welcome to message reprocessing</h1>
    </br>
</body>

This image is not displayed in my browser. When I check my console I have this error:

GET http://localhost:3000/Heading.png 404 (Not Found) 

Please help, thanks

Gurfuffle
  • 784
  • 12
  • 32
DivB
  • 487
  • 2
  • 5
  • 18
  • 2
    The console.log(...) statement won't quite work that way... You can't just add javascript to html. It has to be in a tag and has to be executed in some way. Also, could you post your directory layout here? Are you sure you have Heading.png in your public directory? – xen Jan 20 '14 at 13:47
  • Is the `Heading.png` located at the same folder as `home.html` is? – Rick Hoving Jan 20 '14 at 13:51

6 Answers6

24

First, you have to set the public (folder) as static under server.js file

server.js

// configure our application
const Express = require('express');
const app = new Express();
.......
.......
app.use(Express.static(__dirname+'/public'));
.......

then your img source will be

<img class="logo" src="/images/Heading.png" alt="My_Logo">

and here the folders structure would be -

 project(root folder) \ public \ images\ Heading.png
Soura Ghosh
  • 879
  • 1
  • 9
  • 16
19

Thanks for your answers.I had tried using absolute path already with no luck. However one of my friend suggested as below:

<img class="logo" src="http://localhost:3000/images/Heading.png" alt="My_Logo">

and keep the Heading.png file in public/images directory.

Thanks all.

DivB
  • 487
  • 2
  • 5
  • 18
8

Okay, its not with express.js, but here is a snippet of my code that handles images and external javascripts, but has a protection:

function handler (req, res){
var pathname = url.parse(req.url).pathname;
var isImage = 0, contentType, fileToLoad;
var extension = pathname.split('.').pop();
var file = "." + pathname;
var dirs = pathname.split('/');
if(pathname == "/"){
    file = "index.html";
    contentType = 'text/html';
    isImage = 2;
}
else if(dirs[1] != "hidden" && pathname != "/app.js"){
    switch(extension){
        case "jpg":
            contentType = 'image/jpg';
            isImage = 1;
            break;
        case "png":
            contentType = 'image/png';
            isImage = 1;
            break;
        case "js":
            contentType = 'text/javascript';
            isImage = 2;
            break;
        case "css":
            contentType = 'text/css';
            isImage = 2;
            break;
        case "html":
            contentType = 'text/html';
            isImage = 2;
            break;
    }
}
if(isImage == 1){
    fileToLoad = fs.readFileSync(file);
    res.writeHead(200, {'Content-Type':  contentType });
    res.end(fileToLoad, 'binary');
}
else if(isImage == 2){
    fileToLoad = fs.readFileSync(file, "utf8");
    res.writeHead(200, {'Content-Type':  contentType });
    res.write(fileToLoad);
    res.end();
}

This assuming that you have your app.js and index.html in your root, you can have folders like /css, /img, /js etc. But the app.js and content inside your /hidden folder is unable to reach, but files in your root is still accessable.

BarneyK
  • 389
  • 4
  • 12
2

If you want a quick solution, do this: instead of this <img class="logo" src="./Heading.png" alt="My_Logo"> use:

<img class="logo" src="your file path /Heading.png" alt="My_Logo">

Still not working? check image spelling, file extension(png) because png and PNG are different in live server(case sensitive). and verify

path.join(__dirname, 'public')

too

Vivian
  • 105
  • 6
1

Index.js Inside this file, add the code below to give the directory name to your index.js (server), in a way it is based on your actual directory path.

app.use(express.static(path.join(__dirname, "/public")));

Directory Structure

enter image description here

now inside Index.ejs (you HTML page) add the code below to insert your image and make it visible.

<div id="main-content">
  <img src="img\navthome" />
</div>

Notice inside IMG tag we set the SRC as "img\navthome.gif", here we don't need to declare all the path since we already declared the __dirname, and the PUBLIC folder inside index.js

I hope it can helps you with your issue :D

TBR920
  • 77
  • 7
0

One of the problems I had was that I wanted to define a few specific paths and I found the best answer in the link below. https://www.geeksforgeeks.org/how-to-fetch-images-from-node-js-server/

// Requiring module
const express = require('express');
 
// Creating express object
const app = express();

// Defining port number
const PORT = 3000;                 

// Function to serve all static files
// inside public directory.
app.use(express.static('public')); 
app.use('/images', express.static('images'));
 
// Server setup
app.listen(PORT, () => {
  console.log(`Running server on PORT ${PORT}...`);
})

I did the following in my program:

Shows the structure of folders and files here

 root
   > client
   > node_modules
   > folder_1
   > folder_2
   > package.json
   > server.js

And on my server I define that folder_1 in fl1 path and folder_2 in fl2 path each have a separate static path. And the interesting thing is that I do not use the original name of those folders and I give it my own route.

 // Requiring module
 const express = require('express');
 const path = require('path');

 // Creating express object
 const app = express();

 // http://localhost:3000/fl1/...
 app.use('/fl1',express.static(path.resolve(__dirname,'folder_1')));

 // http://localhost:3000/fl2/...
 app.use('/fl2',express.static(path.resolve(__dirname,'folder_2')));

 // Server setup
 app.listen(3000, () => {
   console.log(`Running server on port 3000`);
 })

After running the server to access this path is enough to use the following path to access its contents.

Note that you must specify the internal routes accurately. For example, the subfolders and file name must be specified. main path /folder_1/img/image_1.png in url /fl1/img/image.png.