Failed to load CSS file in nodeJS application

I followed a tutorial to create a backend app using nodeJS and Express. My MongoDB connection with Mongoose is working fine. However, I am facing issues when trying to add a simple front-end using html/ejs/css. The endpoints are loading on localhost but only the html/ejs files are rendering properly. When I try to load the css file at http://localhost:3000/styles.css, it just shows as plain code without any styling. I am using VS Code for development. Here's my relevant code:

App.js:

const express = require('express');
const bodyParser = require('body-parser');
const product = require('./routes/product.routes'); // Routes for products
const app = express();
var path = require('path');
const cors = require('cors');

app.set('views', __dirname + '/views');
app.set('view engine', 'ejs')

app.use(bodyParser.json());
app.use(bodyParser.urlencoded({extended: false}));
app.use(cors({
    origin: '*'
}));
app.use(express.static(path.join(__dirname, '/public')));
app.use('/product', product);

let port = 3000;

app.listen(port, () => {
    console.log('Server is running on port number ' + port);
});

Product.routes.js

const express = require('express');
const router = express.Router();

// Import the controllers (not created yet)
const product_controller = require('../controllers/product.controller');


router.get('/', product_controller.start);

router.get('/test', product_controller.test);

router.post('/create', product_controller.product_create);

router.get('/:book', product_controller.product_details);

router.put('/:book/update', product_controller.product_update);

router.delete('/:book/delete', product_controller.product_delete);

module.exports = router;

Product.controller.js

const Product = require('../models/product.model');

exports.start = function (req, res) {
    res.sendFile('index.html', { root: './views' })}


exports.test = function (req, res) {
    res.render('index.ejs', { root: './views' })}

Index.ejs

<html lang="en">
  <head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>HTML 5 Boilerplate</title>
    <link rel="stylesheet" type="text/css" href='/public/styles.css'/>
    <base href="/"> 
  </head>
  <body>
    <h1>BookBooker</h1>
      <h2>A library app for personal use.</h2>
      <form action="/create" method="POST">
        <input type="text" placeholder="Writer" name="name" />
        <input type="text" placeholder="Book" name="book" />
        <button type="submit">Submit</button>
      </form>
    <script src="app.js" type="module" type='text/javascript'></script>
  </body>
</html>

Folder structure:

CRUD folder
-app.js
-package.json
-package-lock.json
-controller folder
--product.controller.js
-public folder
--styles.css
-routes folder
--product.routes.js
-views folder
--index.html
--index.ejs

If anyone could provide some guidance on how to resolve this issue, it would be greatly appreciated. Thank you!

Answer №1

Instead of

<link rel="stylesheet" type="text/css" href='/public/styles.css'/>

try using

<link rel="stylesheet" type="text/css" href='/styles.css'/>

The folder name public should not be included in the stylesheet URL, as it is simply the directory where express.static searches for files.

Answer №2

If you encounter CSS displaying as plain text, it could be due to an incorrect Content-type in the header. The browser might be treating it as a regular text file instead of processing it as CSS. To resolve this issue, you can include the following code in your controller before sending the response:

res.header('Content-type', 'text/css');

For more information, refer to the Express Docs

I hope this solution proves helpful.

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

Steer clear of wrapping ng-repeat in nested indexes for routing purposes

I am currently working on an Angular application that displays data in 3 item columns using Bootstrap. To achieve this layout, I have implemented the following code snippet to group my array of data into sets of 3: examples.success(function(data) { $sc ...

The functionality of a generated button has been compromised

My goal is to create a webshop that doesn't rely on MySQL or any database, but instead reads items from JSON and stores them in LocalStorage. However, I've encountered an issue where the functionality of buttons gets lost after using AJAX to gene ...

Start line error in Node.js OpenSSL

Working on my app using node.js for the german Sparkasse (a banking provider) has been quite a challenge. They offer an API for their services, which you can check out here. One of the steps involves obtaining a RSA-2048-SHA1 public key from their ser ...

The object array in Mongoose efficiently stores duplicate date and time values

Here's an example of my mongoose schema: const clothesSchema = new mongoose.Schema({ clothes: [{ _id: { type: mongoose.Schema.Types.ObjectId, ref: 'Clothes' }, dateAdded: { type: Date, default: Date.no ...

How can I extract the "href" attribute from an anchor tag using XPath?

I am working with HTML code that looks like this: <a href="/images/big_1.jpg" class="class-a"> <img class="class-img" src="/images/small_1.jpg"/> <span class="class-span"> <img src="/images/img_1.png"> </ ...

Navigation bar on video player is inverted during streaming of video content

I am currently in the process of developing a video chat application using Node, Express, Socket.io, and WebRTC. I came across this tutorial that has been guiding me through the development process: Link blog While testing my application on Microsoft Edge ...

Using Javascript to retrieve form data from a separate file

I am struggling with my HTML and JavaScript files to collect data. Despite my efforts, the function is not executing properly. Below is the code I have been working on: HTML File : <form class="form-newsletter"> <div class="form-group"> ...

Steps to gather all the images within a directory

Take a look at this demo When you click on the "next" button, new images are loaded from the internet. In my application, all the images are stored in the img/image folder with names like 1.jpg, hi.png, etc. My question is, how can I display these image ...

I'm having trouble sending a string to a WCF service using jQuery AJAX. What's preventing me from sending strings of numbers?

Something strange is happening with my web service when using jquery ajax - I can only pass strings containing numbers. This was never an issue before as I would always just pass IDs to my wcf service. But now that I'm trying something more complex, I ...

Saving data for editing on a Laravel page can be achieved by leveraging the powerful features

I have implemented my create page using vue.js. I called the vue.js file using a component. Now, for the edit page, I followed the same procedure by calling the vue component in the blade. However, I am unsure how to save data for the edit page. Can anyone ...

showing a pop-up message when a specific javascript function is triggered

Here is a unique code snippet showcasing a customized dialog box created with HTML, CSS, and JavaScript. The dialog box is displayed when a button is clicked. <!DOCTYPE html> <html> <head> <style> /* Custom Modal Styles */ .modal { ...

What steps can I take to enhance the efficiency of this JavaScript DOM data manipulation algorithm?

Purpose I am working with a DOM that contains around 70 elements (divs with content). I have the need to move and toggle the display of these divs frequently and rapidly. Speed is crucial in this process. The trigger for moving and toggling these divs is ...

Web Socket functionality may not be able to sense client connectivity loss during internet disconnection

I am looking for a solution to detect when a client disconnects from the internet using web sockets. Here is the code in question: //Include util library var util = require('util'); // Include underscore library var _ = require(&apo ...

What could be the reason for ng-init failing to activate the $watch listener?

When I run the code in my application, there are instances where ng-init fails to trigger the $watch function. Any suggestions on how to fix this? HTML <div ng-controller="MyCtrl"> <p ng-init="stages = 'coco'">{{x}}</p> < ...

`Is there a way to retrieve the ID of an element upon clicking on it?`

Can you help me with a JavaScript query? I have two HTML div elements with ids of 'div1' and 'div2'. When I click on any of the divs, I want to display the id of the clicked div. Any thoughts? <div id="div1"></div> <div ...

Display the printed outcome in a fresh window

HTML: <form id="dbview" method="post" action="core/process.php"> .... <p style='text-align:center;'> <input id='delete' type='submit' name='process' value='Delete selected'/> < ...

When trying to upload a file through input using WebDriver, the process gets stuck once the sendKeys

WebElement uploadInput = browser.findElementByXPath("[correct_identifier]"); uploadInput.sendKeys(elementPath); The script successfully initiates the file upload process, however, the custom JavaScript loading screen persists and fails to disappear as exp ...

JSONP error: "Syntax error - token not expected"

While attempting to perform a JSONP AJAX request, an error was thrown: Uncaught SyntaxError: Unexpected token I'm puzzled about what is wrong in my code. Can someone assist? $.ajax({ url: 'http://api.server32.trustklik.com/apiv1/website/ ...

How to properly size a child div inside a parent container

I'm having trouble with sizing a child div inside a parent div. The problem is that the child div's size changes according to the number of elements it contains, but I want all the child divs to be the same size regardless. This issue arises with ...

The issue of double submission persists, with the prevention of the default action

I'm in need of assistance. Within my form, I have two buttons displayed on the page: "Save" and "Publish". Below is the corresponding HTML code: <button type="submit" class="button">Save</button> <button type="button" class="button" n ...