0

I am trying to get Node to display an HTML file (using fs, http, and express) but the image in that file displays as a broken link symbol.

I have tried writing the following code, I have multiple modifications, but to no avail.

var http = require('http');
var fs = require('fs');
var express = require('express');
var path = require('path');
var dt = require('./modules/myFirstModule');

var port = 3000;

var app = express();

app.use(express.static(path.join(__dirname + 'public')));
console.log(__dirname);
app.use('/images', express.static(path.join(__dirname + 'public' + 'images')));

http.createServer(function (req, res)
{
   //res.writeHead(200, {'Content-Type': 'text/html'});
   console.log("Server Created!");
   fs.readFile('./html/index.html', function(err, data)
   {

       res.write(data);
       res.end();
   });
}).listen(port);
<!DOCTYPE html>
<html lang="en" dir="ltr">
    <head>
        <meta charset="utf-8">
        <title></title>
        <script src="app.js"></script>
    </head>
    <body>
        <img src="images/2016-collage.jpg"/>
    </body>
</html>

I am expecting to see the image displayed on the webpage, but I just get the broken image link symbol.

jonrsharpe
  • 115,751
  • 26
  • 228
  • 437
Bill
  • 1
  • Perhaps this helps: https://stackoverflow.com/a/42000621/3769045 TL;DR `app.use(express.static('public'));` then `` – jdeanwallace Aug 01 '19 at 12:48

1 Answers1

0

I really don't know what you are trying to do in your createServer function, you need to setup routes with express before your clients can make requests. I advise you read the doc a little bit more.

In the end you will need two routes, one to serve the HTML and another to serve the images:

HTML route:

app.get('/', (req, res) => {
    res.sendFile('path_to_html_file.html');
}

Image route:

app.get('/images/:image', (req, res) => {
    res.sendFile(`path_to_your_images_folder/${req.params.image}`);
}
Alexandre Senges
  • 1,474
  • 1
  • 13
  • 22