Images fail to load on a NodeJS server running on localhost

Whenever I attempt to set up a NodeJs server and run it with an HTML file, the images are not loading properly.

Here is the NodeJS code snippet:

var http = require('http');
var fs = require('fs');
fs.readFile('main.html', function (err, html) {
    if (err) {
        throw err;
    }
    http.createServer(function(request, response) {
        response.writeHeader(200, {"Content-Type": "text/html"});
        response.write(html);
    }).listen(8000);
});

The body content in the HTML file looks like this:

<body>
<img id ="gug" src="./gugle.png">
<form>
    <div id = "inp">
    <input type="text" id = "tb" placeholder="Search Results" value="">
    </div>
    <span  style=" margin-left: 420px"> <input type="submit" style = "height: 30px;width: 120px; font-family: Arial; font-weight: bold" onclick="alert_prompt('tb')" value="Google Search">
    <input type="button" style = "height: 30px;width: 120px; font-family: Arial; font-weight:bold" onclick= "lolfnc()" value = "I'm feeling lucky">
    </span>
</form>

<p style="margin-left: 370px; font-family: 'Times New Roman'">
    Google.co.in offered in:<span style="color: blue; font-size: small; font-family: SansSerif"> हिन्दी বাংলা తెలుగు मराठी தமிழ் ગુજરાતી ಕನ್ನಡ മലയാളം ਪੰਜਾਬੀ</span>
</p>
</body>

Both the JavaScript and HTML files are located in the same directory. Any assistance on resolving this issue would be greatly appreciated.

Answer №1

To ensure all assets in your directory are served and to specify the correct MIME type for each file, consider using the 'mime' library which can be easily installed using npm install. Alternatively, you could implement a switch case handling only the specific file types you utilize.

const path = require('path')
const http = require('http');
const fs = require('fs');
const mime = require('mime');

http.createServer(function(request, response) {
    var filename = 'public'+request.url;
    if (fs.existsSync('public'+request.url)) {
        var fileExtension = path.extname(filename);
        var mimeType = mime.getType(fileExtension);
        response.writeHead(200, {"Content-Type": mimeType});
        var data = fs.readFileSync(filename);
        response.end(data);
    } else {
        //404 not found error
        response.writeHead(404, {"Content-Type": "text/html"});
        response.write("<h1>404 Not Found</h1>");
        response.end();
    }
}).listen(80);

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Retrieve the current domain name (server name) within a Shiny application

I am managing 3 servers - alpha, beta, and gamma. The goal is to deploy my Shiny code from the alpha server to the gamma server. However, I encounter a challenge. In my ui.R file, I reference another site called start using href = 'https://alpha.com/ ...

The problem of Rails redirect_to not working with anchor and will_paginate gem

In my posts controller, I have implemented a feature where upon updating a post, it redirects to the specific post using an anchor tag. The challenge arises when dealing with pagination through the will_paginate gem. I have set up pagination to display fou ...

SweetAlert2 not displaying properly in Ionic6 - troubleshooting the issue

My current project is an Ionic 5 Angular project with SweetAlerts2 popups. Recently, I decided to upgrade to Ionic6 and encountered an issue where the SweetAlerts2 popups are not displaying correctly. The alert seems to only show up in the header, leaving ...

When hovering over different <a> tabs, showcase various images in individual <div> sections

Here are the buttons I am working with - <div class="nav nav-tabs " id="nav-tab" role="tablist"> <a style="text-decoration:none" class="nav-item nav-link" data-toggle="tab& ...

Close any open alerts using Protractor

While using protractor and cucumber, I have encountered an issue where some tests may result in displaying an alert box. In order to handle this, I want to check for the presence of an alert box at the start of each test and close/dismiss it if it exists. ...

Using .change(); in JavaScript code with jQuery does not trigger a function

Here we have a generic code example for a jQuery function: $(document).ready(function() { if (something) { // This does something } else if (something else) { // This does something else } else { // And this does somethin ...

Apply express middleware to all routes except for those starting with /api/v1

Is it possible to define a catchall route like this? app.get(/^((?!\/api/v1\/).)*$/, (req, res) => { res.sendFile(path.join(__dirname, '../client/build', 'index.html'));}); ...

Displaying information on a chartJS by connecting to an API using axios in VueJS

Struggling with inputting data into a ChartJS line-chart instance. The chart only displays one point with the right data but an incorrect label (named 'label'): Check out the plot image The odd thing is, the extracted arrays appear to be accura ...

Check MongoDB to find out if today's date falls within two specific columns

I'm encountering unexpected outcomes when trying to retrieve collections between two columns. The collection I am working with looks like this: { UserID: "1", StartDate: "2021-04-15", EndDate: "2022-01-18" } { Us ...

Nested Popper component in MATERIAL-UI React - a Popper within a Popper

I am currently developing a calendar application. The issue at hand is that when clicking on a popper within another popper, both poppers close. This happens because the click outside event of the first popper triggers and closes it. I have a component c ...

Extracting information from this array using JavaScript

After struggling for a day, I finally managed to get some output from PHP instead of just the word "array". What a relief! (check out this link for the solution) Basically, this is the data returned from an XMLHTTP request to PHP, handled through a JS ca ...

Troubleshooting: GSAP Scrolltrigger malfunctions when using multiple triggers

Having multiple triggers with different functionalities: Show or remove a canvas Change the background color of a section Play or pause video when in view Play or pause CSS animation The first two triggers work fine individually, but I am encountering an ...

Sass does not compile for optimization

My Sass compiler generated an overly large file for me, but it could be much smaller!! I checked the compiler settings and didn't find anything wrong! The issue might be with the compiler itself. It's also possible that there is a problem with my ...

CSS positioning problems thoroughly elucidated

I'm facing two issues that I can't seem to resolve. My goal is to recreate a design similar to the one found at https://i.sstatic.net/XfPqm.jpg. My first issue is with adjusting the box in the header to stay aligned next to my headline tags. The ...

Having trouble sending data from Node.js to Jade template engine

Here are a few lines of code I have: var base="http://www.youtube.com/watch?v="; var videoID=result.items[0].id.videoId; var link=base+videoID; console.log(link); When I check the console log, I can see the value of the variable "link" perfectly fine. Ho ...

Tips for aligning divs side by side with smaller divs stacked below them

I have a collection of dynamically generated divs that act as panels for selecting different options. These divs can be categorized into two types: regular and short. The height of the regular divs is determined using JavaScript to match the height of the ...

Need help resolving a JavaScript error while implementing ToolScriptManager for UpdatePanel in my project

I am attempting to register the following JavaScript code in order to add freeze functionality to a GridView. However, when trying to compile, I encounter the error message 'Microsoft JScript runtime error: 'Sys' is undefined' How can ...

What is the most effective method for digitally collecting a signature?

Currently, I am in the process of developing a website application using PHP that demands a signature from the user. This particular section of the website will only be accessible on Windows-based tablets. Hence, my inquiry is as follows: What method wo ...

Cease the use of jQuery animations

My JavaScript code snippet looks like this: $.get("/<page>.php", "userid='.$userid.'&"+status, function(data){ $("#status").show("fast").html(data).delay(4000).hide("fast"); }); On a page with multiple links triggering thi ...

``Why is it that the JavaScript code is unable to find the maximum or minimum sum? Let's

function calculateMinMaxSums(arr) { // Custom code implementation let max = Math.max(...arr); let min = Math.min(...arr); let minsum = 0; let maxsum = 0; for (let x in arr) { if (arr[x] != max) { minsum += arr[x]; }; if (arr[x ...