Troubleshooting CSS pathing problem in Node.js web app hosted on A2 Hosting

I am currently learning node.js and still relatively new to it. Please excuse me if my first question is inefficient or poorly formatted. I am trying to upload a one-page test to explore A2's node.js service.

Following tutorials from A2 on creating a Node.js application with cPanel using Node.js Selector (here) and syncing git repositories (here), everything works except the main page located in dirname/repositories/test/views/home-visitor.ejs does not read the uploaded CSS file (located in: dirname/repositories/test/public/main.css) and some images do not load, despite correct folder paths.

The node.js app appears as plain HTML only. The same app/git repository works fine on Heroku, reading CSS and displaying all images. I am trying to diagnose pathing issues specific to A2's hosting service.

Browser console messages for the non-working app page include:

"Refused to apply style from 'http://domainname.com/main.css' because its MIME type ('text/html') is not a supported stylesheet MIME type, and strict MIME checking is enabled."

Failed to load resource: the server responded with a staus of 404 () nonWorkingImageExample.png:1

Failed to load resource: the server responded with a staus of 404 () anotherNonWorkingImageExample.png:1

leads to a 404 page

app.js:


const express = require("express")
const app = express()

let port = process.env.PORT
if (port == null || port == "") {
  port = 3000
}

app.use(express.static("/public/"))
app.set("views", "views")
app.set("view engine", "ejs")

app.get("/test", function (req, res) {
  res.render("home-visitor")
})

app.listen(3000)

The page I am testing: home-visitor.ejs:

<!DOCTYPE html>
    <html><head>
        <meta charset="UTF-8">
        <meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
        <meta name="viewport" content="width=device-width,initial-scale=1">
            
        <link rel="stylesheet" href="main.css" type="text/css">
    </head>
    <header>          
        <div class="forMobile mobileHeader">
            <div class="mobileLogo">
                <a href="#"><img src="images/workingImageExample.png" alt="Image Description"> 
                </a>
            </div>
        </div>  
    </header>
            
   <div class="forDesktop centerContent tempMssg">"Lorem flexitarian salvia offal umami. Sartorial swag drinking portland cray. Godard jianbing retro thundercats hella tilde. "
            
        <br><br> 
        <a href="#" target="_blank" rel="noopener noreferrer">
            <img src="images/nonWorkingImageExample.png" alt="Twitter Logo Link" width="35px" height="35">
        </a>
    </div>                  
    <div class="forMobile mobileUpperBG">
        <img src="images/anotherNonWorkingImageExample.png" alt="upper left bg image">
    </div>
</html>

If anyone familiar with hosting node.js apps on A2 can provide assistance, I would greatly appreciate it. Thank you for taking the time to read through my question.

Answer №1

All credit goes to the amazing VictoryFlame for providing the solution in their enlightening video tutorial https://www.youtube.com/watch?v=BAD5JyOymRg.

After some troubleshooting, I made changes to the pathing of my public folder in app.js and adjusted how I linked CSS and image files in my .ejs file:

Here's the updated snippet from app.js:

const express = require("express")
const app = express()
const path = require("path")

app.set("views", path.join(__dirname, "views"))
app.set("view engine", "ejs")

app.use("/test1/static", express.static("public/"))

app.get("/test1", function (req, res) {
  res.render("home-visitor")
})

app.listen()

I restructured the style link for the CSS page and adopted a new syntax for linking images:

From home-visitor.ejs:

<link rel="stylesheet" href="https://domainname.com/test1/static/home.css">

<a href="#" target="_blank" rel="noopener noreferrer">
<img src="/test1/static/images/imageWorksNow.png" alt="Twitter Logo Link" width="35px" height="35"></a> 

Everything is now properly served and displayed as intended. Hopefully, this solution will be beneficial to someone else down the road!

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

Steps to resolving the error "Unable to modify headers after they've been sent to the client"

I'm encountering a new error for the first time. I can see the data in the console, but when I try to use res.json(), it displays null. How do I resolve this issue? const fetchClientData = async (req: Request, res: Response) => { const { clientId ...

ExpressJS: Leveraging Dynamic Routing for Post and Put Requests

My tech stack includes Angular on the front end and Express on the back. I am facing a challenge with having two forms on a single page that need to post to the same URL, but trigger different controller methods based on a variable from the request body. ...

The node and npm versions are identical, yet the package.lock file differs

Our team is working on a React project with the same Node version (18.16.1) and NPM version (9.5.1). However, when I clone the repository and run `npm install`, I am getting a package-lock file that differs from the rest of the team's. What could be c ...

"Object.entries seems to be returning only the initial object in the list

This is my object var obj = { "first_obj": { "a":1, "status": 1 }, "second_obj": { "a":2, "status": 3 } } I'm struggling to loop through this object using foreach and Object.entries, as the latter only returns the first object. How ...

Unable to deploy Bower on Azure successfully

I have chosen Azure to deploy my Node.js web application, and I've connected Github as the deployment repository. Following Jay Harris's instructions on this webpage, I have set up deploy.sh for deployment. My web application relies on bower, bu ...

Files that have been uploaded are now being showcased in the browser with base64 data

I am currently utilizing couchdb to store attachments that need to be displayed in the browser. The data is uploaded from an HTML input and then processed once saveDoc function is called: getFileData: function(file){ var reader = new FileReader(); ...

issue occurred when executing the command "grunt serve:dist"

I utilized the mean stack seed by following this link: https://github.com/angular-fullstack/generator-angular-fullstack However, when attempting "grunt serve:dist," I encountered the following error: Running "ngAnnotate:dist" (ngAnnotate) task >> 2 ...

Server crashing as nodemon encounters mongoose issue

Currently, I am in the process of learning Node JS, Mongodb, and Express JS. My goal was to create a database using Mongodb Compass and store some data within it. However, every time I attempt to run my code, my nodemon server crashes after a few minutes o ...

Encountering a 127 error when trying to install npm on an EC2

I’m currently in the process of setting up npm on my Amazon EC2 instance. So far, I’ve successfully installed both Git and Node.js on the instance. This is the series of commands I used: git clone git://github.com/joyent/node.git cd node git checkou ...

The unique identifier for retrieving an object from the database is dynamic and subject to change with each

Click here for image description I am currently building an app using Express and Mongoose MongoDB. However, when I try to access /musics/:id to go to the details page, the app redirects me to the correct page but crashes because the id is being changed. ...

Having issues with sendPhoto functionality on node.js using the telegram-api and node-canvas libraries. It seems to be malfunctioning and not producing any error

Developing a test telegram bot that generates a picture with a random number and sends it to a chat has been a bit challenging. To simplify the deployment process, I decided to use Docker to build an image (based on the aws node image) and deploy it to a l ...

Validating JSON against a JSON schema using JavaScript

My current task involves validating approximately 100 JSON Objects against a specific JSON schema to ensure that all fields and their types align with the schema requirements. Initially, I attempted to use a JSON schema generated from a website. However, ...

MERN application encounters error with running "heroku-postbuild" script during deployment on Heroku platform

During the process of deploying my app to Heroku, everything seems to be running smoothly until I encounter an issue. After logging in, I execute a series of terminal commands for deployment and receive the following responses: heroku login heroku: Press a ...

Running a Node.js child process upon clicking an HTML button

I need to create a basic webpage where clicking a button will open the command prompt. This is my goal. Below are the HTML and Node.js code snippets. test.html <html> <head> </head> <body> <p>guru</p> <form a ...

Encountering difficulties installing socket.io using npm on Centos 6.4

Currently in the process of setting up socket.io via npm on a fresh Centos 6.4 (running on a virtual machine). (using root access temporarily for testing purposes) [root@localhost lib]# npm cache clean [root@localhost lib]# npm install socket.io npm http ...

Having trouble importing Sequelize models in TypeScript: encountering an error stating that no Sequelize instance was provided

Here is the content of my user.model.ts file: @Table export class User extends Model<User> { @Column({ allowNull: false }) firstName: string; @Column({ allowNull: false }) lastName: string; ... Upon attempting to import it, I encou ...

The integration of angularFileUpload seems to be malfunctioning

This question may seem simple, but I am new to using Angular. My goal is to upload images on my website using AngularFileUpload. Here is what I did when initializing my app: var app = angular.module('myApp',['ui.router'],['angular ...

Visual Studio Project Alert: Node.js Absent of NPM

I'm currently exploring a beginner's guide on setting up a Node.Js project in Visual Studio. After creating the project, I noticed an "npm" folder containing packages like body-parser, cookie-parser, but all marked as "(missing)". Despite repeati ...

Encountered an error while attempting to load the user into the session

Testing my authentication, I randomly created a user with the login 8===D and password 123. However, when I tried to log in, passportjs failed to serialize that user. But when I used a regular username like [email protected], it worked fine and serial ...

Using ES6 to Compare and Remove Duplicates in an Array of Objects in JavaScript

I am facing a challenge with two arrays: Array One [ { name: 'apple', color: 'red' }, { name: 'banana', color: 'yellow' }, { name: 'orange', color: 'orange' } ] Array Two [ { name: &apos ...