I am encountering difficulties displaying the image and CSS files from another folder in my HTML with Node.js

I am facing difficulty in establishing a connection between my front-end and back-end using node.js. As a result, the website only displays the HTML code without linking to the CSS or image files. Here is the folder structure:

root
-src
•picture
○jpg/png file
•css
○css file
•html
○html file
-ws_src
•this file.js
•package.json

const express = require("express");
const path = require("path");
const http = require("http");
const fs = require("fs");
const app = express();
app.use(express.static(path.join(__dirname, '../src/css')));
app.use(express.static(path.join(__dirname, '../src/picture')));

const myQ1Server = http.createServer((req, res) => {
    const userPath = req.url; 
    if (userPath === "/") {
        fs.readFile("../src/html/HtmlMainpage.html", function (err, data) {
            console.log("Request at: " + userPath);
            res.statusCode = 200;
            res.setHeader("Content-Type", "text/html;charset=utf-8");
            res.write(data);
            res.end();
        });
    } 
    
    else if (userPath === "/HtmlAboutuspage.html") 
    {
        fs.readFile("../src/html/HtmlAboutuspage.html", function (err, data) {
            console.log("Request at: " + userPath);
            res.statusCode = 200;
            res.setHeader("Content-Type", "text/html;charset=utf-8");
            res.write(data);
            res.end();
        });
    } 
    
    else {
        console.log("Request at: " + userPath);
        res.statusCode = 404;
        res.setHeader("Content-Type", "text/plain");
        res.write("404 file not found!");
        res.end();
    }
 
});
console.log("Listening on port 3030");
myQ1Server.listen(3030);

Answer №1

  1. Organize all your project files into a folder and give it a name, such as assets
  2. Use relative URLs like ./assets/style.css or ../assets/script.js then incorporate this into your Node.js code
app.use(express.static("/path/to/assets"))

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

What function does the sx prop serve in Material UI?

<Container style={{ margin: "10px" }}> <Article post={post} setCurrentId={setCurrentId} /> </Container> <Container sx={{ margin: "10px" }}> <Article post={post} setCurrentId={setCurrentId} /> </Cont ...

Guide on setting a cookie on ".localhost" using an express/node application in order to make it accessible from "something.localhost"

I have a node/express application running on www.localhost:1234. I am attempting to set an httponly cookie from express with the domain ".localhost" so that I can access it on subdomains like "something.localhost:1234" or "something.localhost:1234". Howeve ...

What is the best way to retrieve all post data in my MERN application?

I have been developing a MERN App which is a simple project enabling users to log in and create posts from their accounts. Users can also follow other users, and on the homepage they can view their own posts as well as posts from friends. Currently, I am ...

How does leaving a comment in a different file impact the overall design of the app in Next.js?

I'm currently working on integrating light and dark themes into a Next.js application. For this, I am utilizing TailwindCSS in combination with next-themes. Strangely enough, even though my system preference theme is set to dark mode, the page initial ...

AngularJS factory or filter failing to update properly

I have been working on a system that manages translations in my factory. I set the language as a string and then use a filter to update the view when the language changes. Everything works fine if I define the language in the view beforehand, but when I t ...

Is it possible to decrease the size of a div by scrolling both vertically and horizontally?

Can a div's height and width both be reduced at the same time while scrolling down a page? Let's say that as the user scrolls, the size of the div changes from 400px by 400px to 200px by 200px, all while remaining centered on the page. I've ...

Discovering the smallest, largest, and average values across all properties in an array of objects

Given an array of objects with varying values, the task is to determine the minimum, maximum, and average of the properties in that array. For example, consider the following array: const array = [{ "a": "-0.06", "b": "0.25", "c": "-0.96", ...

Executing a script for every row in a table using Python and Selenium

As a newcomer to Python and Selenium, I have been struggling with a specific task for days now. Despite my efforts to search and experiment, I find myself completely stuck. My goal is to access sales records within a table that contains information about ...

Issue with VueJS where changes made to properties in the mounted hook do not properly trigger the

I'm working on a VueJS component that features a button with computed properties for its class and text. These properties change every time the button is clicked, updating smoothly with each interaction. However, I've encountered an issue when at ...

Strategies for dynamically incorporating customized text with unique ID attributes using jQuery while ensuring accuracy

I have a variety of divs structured like this: <div class="textwidget"><div> <div class="textwidget"><div> <div class="textwidget"><div> Here is the desired output for the divs: <div class="textwidget" id="widget-1 ...

Is there a way to extract a specific element from an array stored within a form element's value?

I am encountering an issue with retrieving values from an array in an HTML form element using jQuery. Despite my efforts to explain and provide code, I am not getting the desired results. Can someone help me understand what is going wrong in my code? Thank ...

Using 'require' within a nested directive that relies on the parent directive in AngularJS

Implementing a sub directive to be utilized in multiple directives is my current challenge. These parent directives share a common controller that has useful methods for updating scope variables within these directives: (potentially changing controllers ...

Angular's separate scope variables allow for isolated data manipulation within individual components

Struggling with one scope variable affecting multiple elements in a div in AngularJS. Looking for help as a beginner in handling this issue. For a clearer understanding, here's an example: JS: /* controller-home.js ********************************* ...

Why does the DropDownList consistently remove the initial value?

I am currently in the process of developing a recipe website focused on meals. I have created an admin panel where I can manage the meals added to the site. One issue I am facing is with deleting a meal that was previously added. The menu displays the numb ...

Is it possible to make each letter on a page a different color using JavaScript? I've noticed that there is always an additional set of span tags before each opening tag on the page

Page hosted using Google Drive Within the JS code: var doc_part = false; //denotes if a character is not part of the visible document var page_body; //function to generate random rgb values function randomInt(max, min) { return Math.floor((Math.ran ...

Following an AJAX request, jQuery.each() does not have access to the newly loaded CSS selectors

Note: While I value the opinions of others, I don't believe this issue is a duplicate based on the provided link. I have searched for a solution but have not found one that addresses my specific problem. Objective: Load HTML content to an element u ...

Enhance a Javascript object by dynamically introducing new elements

I am currently working on a webpage using HTML and jQuery. My goal is to create a form where users can enter an email address in a textbox, and when they click a button, the email should be added to an object that displays all the emails entered so far. Th ...

What are the appropriate levels of access that an operating system should provide for web-based scripting?

Contemplating the level of access web-based applications have to an operating system has been on my mind. I'm pondering: What is the most effective method for determining this currently? Are we seeing a trend towards increased or decreased access? ...

Cross domain Ajax POST requests using CodeIgniter and AjaxBy utilizing CodeIgn

Initially, I would like to clarify ... I own two domains: www.one.com and www.two.com The first domain www.one.com has a form input below <div class="hidden cswrap2"> <h3>Edit Data Mustahik</h3> <div class="cscontent"> ...

What could be causing the request.body to be considered as undefined?

My server has a node-js setup with bodyparser and other modules: var express = require('express'); var dbcon = require('./app/db/databaseconnection'); var bodyParser = require('body-parser'); var app = express(); var router ...