unable to locate public folder in express.js

I recently created a basic server using Node.js with Express, and configured the public folder to serve static files.

Within my main index.js file, I included the following code:

const express = require('express');
const app = express();
const http = require('http').Server(app);
const fs = require('fs');

app.use(express.static(__dirname + '/public'));

app.get('/', (req, res) =>  {
    res.sendFile(__dirname + '/public/index.html'); 
});

http.listen(3000, () => console.log('server started on *:3000'));

The directory structure is as follows:

root 
|---index.js
|---package.json
|---public
|   |---index.html
|   |---cs
|   |   |---index.css
|   |---js
|   |   |---index.js

Inside the index.html in the public folder, I added this code snippet:

<head>
    <script src="js/index.js"></script>
    <link rel="stylesheet" src="css/index.css" type="text/css" >
</head>

Despite this setup, the CSS is not rendering properly. Any suggestions on how to fix this issue?

Answer №1

Make sure to swap out the src attribute with href in the link tag. If that doesn't resolve the issue, try the alternative solution provided below.

Assuming your server is operating on http://localhost:3000/

To fix this, update the URL specified in the src of your index.html located in the public folder by appending it with the base URL like shown here:

<head>
    <script src="http://localhost:3000/js/index.js"></script>
    <link rel="stylesheet" href="http://localhost:3000/css/index.css" type="text/css" >
</head>

Answer №2

Consider updating this:

app.use(express.static(__dirname + '/public'));

With the following:

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

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

With the use of discreet JavaScript, the parameter is not empty; instead, it contains values

Previously, my JavaScript code was functioning correctly when it was within the same page as my cshtml file: function SaveEntity() { // more code here alert(entity.FirstName); /* this shows that entity's properties have values */ $.post( ...

Is there a way to fix the error "The requested resource does not have the 'Access-Control-Allow-Origin' header" within Express using Firebase functions?

Trying to send an email through nodemailer using Firebase functions, but encountering errors. The data for the email will come from a form. Error message: Access to XMLHttpRequest at 'my-firebase-functions' from origin 'my-angular-web-app&a ...

How can I update the title of the NavigationBarRouteMapper without altering the current route in React Native?

Here is a snippet of code that outlines the NavigationBarRouteMapper: var NavigationBarRouteMapper = { ... , RightButton(route, navigator, index, navState){ return( <TouchableHighlight onPress={()=>{ //When this ...

Creating stylish rounded corners for the table header with a specific background color using CSS

I am a beginner in HTML/CSS and I am trying to create a table with rounded top corners and a different background color for the header line. I have been able to achieve each individually with the help of online resources but I am struggling to combine the ...

Incorporating interactive maps into an AngularJS web application

I've been attempting to integrate Google Maps into my AngularJS application, using the script tag below: <script src="https://maps.googleapis.com/maps/api/js?key=[MySecretKeyHere]&callback=initMap" async defer></script> I found this ...

Unable to install packages using npm due to ECONNRESET error when not using a proxy

Initially, I smoothly utilized node.js for installing various packages via npm without encountering any issues. However, the scenario took a turn when, despite no alterations in my settings (Win8; devoid of proxy and functional internet connection), I enco ...

Having trouble adding local modules to the package.json dependency list? Check if the issue is caused by the defined file

In the main directory of my application, I currently have the following package.json file. .... "dependencies": { "LessonApi": "file:apis/lesson", "SearchAPI": "file:apis/search", "SlotApi": "file:apis/slots", "UserAPI": "file:apis/user", "bcrypt": "^0.8. ...

I encounter an error in my JavaScript function indicating that it is not defined

let element = document.querySelector("#value"); let buttons = document.querySelectorAll(".btn"); buttons.forEach(function (button) { button.addEventListener("click", function(event){ console.log(event.currentTarge ...

Learn how to toggle the visibility of three div elements arranged horizontally

$(document).ready(function () { $("#toggle").click(function () { if ($(this).data('name') == 'show') { $("#sidebar").animate({ width: '10%' }).hide() $("#map").an ...

What is the best way to incorporate a custom string into an Angular application URL without disrupting its regular operation?

In my Angular application with angular ui-router, I am facing an issue with the URL structure. When I access the application from the server, the URL looks like localhost/..../index.html. Once I click on a state, the URL changes to localhost/.../index.htm ...

Next-Auth: Access Session in _app.js Directly Without Using getServerSideProps

When working with React.js and React-Auth, it's important to note that calling server-side functions such as getServerSideProps can prevent you from exporting your project using next export. Below is the content of my pages/_app.js, which I structured ...

Ways to resolve NPM dependency conflicts

Attempting to set up all the necessary npm packages for the AWS sample demo found at https://github.com/aws-samples/amazon-chime-sdk-classroom-demo on my laptop has been a bit challenging. Every time I try to run npm install I can't help but wonder i ...

Analyzing the different NodeJS drivers and modules available for connecting to SQL databases

We have a new nodejs project in the works, but we're faced with the task of selecting modules and drivers to integrate with our existing MS SQL database. Researching and comparing all the available tools can be quite tedious, especially when trying to ...

Using HTML: The trick to obtaining selection offsets in relation to HTML tags

Let's say I have HTML code like this: <div> <p> start<span>span</span>end </p> </div> I am looking for a way to retrieve the offsets when text is selected, while still taking into account the presence of span ...

How can I display a nested div when the parent div's v-if condition is not met?

In my project, I am utilizing Laravel 6 in combination with Vue.js 2. To iterate through users and showcase their information within div elements, I am using a for loop outlined below. The Category names are stored in user.pivot.demo2, and the users are ...

Slice an interactive div

I am currently working on setting up a horizontal sliding div for a menu. The layout consists of a left DIV that remains visible at all times, and a sliding DIV that appears horizontally when the menu is activated. My HTML code looks like this. <div id ...

Invoke the wrapper function within the jQuery AJAX `complete` callback

I am currently trying to accomplish a task, but I keep receiving an error message stating that I cannot bind to undefined. I suspect this is happening because I am working within an anonymous function. My goal is to be able to access the method (getAndSayH ...

Positives and negatives images for accordion menu

I have successfully created an accordion list using HTML, CSS, and JavaScript. However, I would like to enhance it by adding a plus and minus picture in the left corner of the heading. Is there a way to achieve this functionality? I have two images that I ...

Styling the topbar with CSS includes adding a vertical separator that neatly wraps the content within the

I recently created a website using HTML and CSS, featuring a topbar. However, I encountered an issue while trying to insert a vertical separator between some of the icons within the topbar. Initially, when I added the separator-div, only the first three ic ...

What is the process of utilizing app.get to direct to a different webpage within Node.js and express?

I've been experimenting with app.get in order to navigate to a different HTML page. For example, I'd like typing localhost:3000/newpage to redirect me to newpage.html So far, I've only managed to route to another JS file using app.get. Is t ...