There was an issue encountered while working with Node.js: Unable to load resource - the server returned a 404 error (Not Found)

Hello everyone, I hope you're all well. I have a question regarding creating a navigation bar and serving it on my server. Every time I try to do so, I am getting a 404 not found error. However, I have placed my logo file in the same directory as my HTML code, which looks like this:

<!DOCTYPE html>
<html>
    <head>
        <meta charset="utf-8">
        <meta http-equiv="X-UA-Compatible" content="IE=edge">
        <title>Discord Chat</title>
        <link href="https://fonts.googleapis.com/css2?family=Karla&display=swap" rel="stylesheet">
        <link rel="icon" href="logo.png">
        <style>
            * {
                margin: 0px;
                padding: 0px;
                font-family: 'Karla', sans-serif;
            }

            #logo {
                width: 50px;
                height: 50px;
                border-radius: 30px;
            }

            .navbar ul{
                position: sticky;
            }

            .navbar ul li a{
                text-decoration: none;
                text-transform: none;
                color: lightseagreen;
            }

            .navbar ul li{
                list-style: none;
                display: inline;
                position: relative;
                top: -30px;
                left: 71px;
                padding: 20px;
            }

            .navbar{
                background-color: black;
                opacity: 0.6;
            }

            .navbar ul li:hover {
                cursor: pointer;
                border-radius: 50px;
                animation-name: navanim;
                animation-duration: 5s;
                animation-iteration-count: 1;
                font-size: 20px;
            }

            @keyframes navanim{
                from{
                    background-color: white;
                    color: black;
                }
                to{
                    background-color: black;
                    color: white;
                }
            }
        </style>
    </head>
    <body>
        <nav class="navbar">
            <img src="logo.png" alt="Discord Chat" id="logo">
            <ul>
                <li><a href="index.html">Home</a></li>
                <li><a href="about.html">About</a></li>
            </ul>
        </nav>
    </body>
</html>

And here is my server-side code:

var app = require('express')();
var http = require('http').Server(app);
const port = 8000;


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

http.listen(port, function(){
    console.log(`Server is listening on https://127.0.0.1:${port}/ `);
});

Any ideas on how I can successfully display my logo on my website?

Answer №1

To serve static files using Express, you have to set it up properly. As per the documentation, you can achieve this by adding the following code snippet:

app.use(express.static('public'))

This piece of code will make files within the 'public' directory accessible relative to the location of your code. For more detailed instructions, visit https://expressjs.com/en/starter/static-files.html.

Make sure not to take any shortcuts when importing Express. Ensure that your code begins with the following lines:

const express = require('express')
const app = express()

Rather than using var app = require('express')();, which might cause issues.

Answer №2

If your logo file is located in the same directory as the other files, you can access it by using this method.

express.static(__dirname).

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

Can a circular dependency be tolerated when a type declaration file brings in an enum from the implementation?

Let's say you have an implementation file called module.ts and a type declaration file named module.d.ts. // module.ts import type ConfigI from 'module.d.ts'; export enum ConfigType { Simple, Complex } function performTask(config: Conf ...

Enhanced Button Dropdown Function

I have the following HTML code: <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Expanding Dropdown Menu</tit ...

What could be causing my external JavaScript file to not function properly upon loading my HTML file?

I have organized my code by separating the HTML and JavaScript portions. The JavaScript code is now in its own separate file and I use 'script' tags to reference it in the HTML file. Within the JavaScript code, I have two functions - one creates ...

Customizing Material UI Components: Implementing the onChange Method

I've been working with the materia kit react template from creative-tim: However, I noticed that the customerInput component in this template lacks an onChange method. Does anyone have a solution for handling user inputs using this specific template? ...

Is there a method to save the req object from a callback route to a file using NodeJS?

I have a requirement to save my req/res object to a file for future reference when redirecting to a specific page. Here is what I attempted: app.get("/route", function(req, res) { res.render("route"); fs.writeFile('./data.json', JSON.stringify ...

Alert Box Displays Variable Name Instead of Label Name in Form Validation - MM_validateForm()

Looking at the screenshot, you can see variable names such as "email_address", "email_message" and "email_subject". I would like these to be displayed as "Email", "Message" and "Subject" instead. The validation in this form is done using MM_validateForm() ...

Modify the color of the div element after an ajax function is executed

My original concept involves choosing dates from a calendar, sending those selected dates through ajax, and then displaying only the chosen dates on the calendar as holidays. I aim to highlight these selected dates in a different color by querying the data ...

"Stay up-to-date effortlessly with the latest information on ext.data.store through automatic

I am working with an ExtJS data store mystore= Ext.create('Ext.data.Store', { id: 'store_id', fields: ['label', 'value', 'id', 'type'], autoLoad: true, proxy: ...

When the mouse hovers over, the flash content in Firefox 7 will automatically reload

This is the structure I currently have: <div class="feed-item" style="position:relative;" id="feed-611" onmouseover="showDelete()" onmouseout="hideDelete()"> <div class="feed-avatar"> AVATAR </div> <div class="feed-content"> ...

Error: Mongoose failed to cast DBrefs value to ObjectId

I am facing an issue with my Team Schema and Match Schema setup. I want the home/away teams in the Match Schema to refer to the Team object. However, I am encountering an error while trying to save the Team. I suspect there might be an issue with the Schem ...

Error: Unable to access the 'rotation' property of an undefined object in the animate function on line 266 of index.html, at line 287 of index.html

I am facing an error when trying to animate a model with rotation or position in my code. I attempted to create an init function to run everything, but it did not resolve the issue. The error only appears during animation; once the animation stops, the e ...

"Unexpected error: .jqm is not defined as a

Having an issue with a jqm function that I need help with. <span class="smaller gray">[ <span class="blueonly"><a href="javascript:void(0)" rel="nofollow" onclick="javascript:jQuery(\'#s ...

Create an animation effect where a div increases in height, causing the divs beneath it to shift downward in a

My aim is to create columns of divs where the user can click on a div to see more content as the height expands. I've managed to set this up, but it seems there's an issue with the document flow. When I click on a div in the first column, the div ...

Add movement to elements as you scroll down the page with Angular

We are utilizing Angular.js combined with Bootstrap, and there is no jQuery included in our project. I am interested in implementing animate.css to create a fading effect for elements on the page as users scroll up and down. I came across an example that ...

React and Next.js: Excluding transmission of cookies from server-side to backend

My setup involves using Kubernetes for managing the backend (microservices) and React for the client-side. I am facing an issue with authentication - I can successfully send and authenticate via cookies when the request is initiated from the browser (clien ...

The database is experiencing issues and new data is unable to be inserted into Firebase

I recently attempted to add offers to the database using the code in my 'addoffer.html' file, but I encountered an issue where the offer was not being successfully added. I'm struggling to identify where I may have made a mistake in the codi ...

Retrieving information from JSON files related to table objects

How to Display JSON data in a Table? I am facing difficulty accessing my JSON data as it is nested within an array of objects. How can I retrieve this information? Currently, I am using the map function to display only the name and avatar, but the data s ...

Is it possible for the `findIndex` method in EcmaScript6 to return multiple values at once

When delving into ES6, I came across a situation where I needed to find the index of multiple items in an Array. However, I found that it only returned the index of the first item that matched my condition or callback function. For example, let's say ...

The only functioning href link is the last one

Currently, I am in the process of constructing a website using HTML and CSS. My goal is to create a white rectangle that contains 4 images, each serving as a clickable link redirecting users to different sections on the page. The issue I am facing is that ...

Unusual Actions: Removing a specific item from an array using ReactJS

In my current approach, I am utilizing a technique to remove an object from an array stored in the state: export default function App() { const [gridData, setGridData] = useState({field1:"Placeholder",data:[]}); const data = [ { numstart: 1,numend ...