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

Securing your application with SocketIO and MySQL authentication

I have successfully established a connection between my app and a MySQL DB using socketIO. However, I am facing an issue where I am unable to pass the authentication status of the user into the connection part of socketIO. In my app, there are hosts and vi ...

What is the best method to activate a JavaScript function after 1 minute of user inactivity?

I need to set up a web page where a JavaScript function is activated after 1 minute of user inactivity. The page primarily features the <form> component. What's the best way to implement this type of function? ...

How can you utilize an Express server to redirect a NuxtJs application?

My NuxtJs application is set up with an Express server using npx create-nuxt-app <project-name>. The configuration allows for server-side rendering. The Express server has access to NuxtJs middleware, as shown below: app.use(nuxt.render) I have cr ...

Can you explain the purpose of the datalayer.push function?

I've been puzzling over this.. It seems like data layer.push is simply updating the second amount. Can someone shed light on what exactly is happening here? function dollarz() { var amount1 = '$156.86'; var amount2 = amount1.replace(&quo ...

Converting JSON data into a JavaScript array and storing it in a variable

Currently, I am delving into the world of JavaScript and my instructor has assigned a task that involves utilizing information from a JSON file within our JavaScript code. The issue I'm facing is deciphering how to effectively convert the JSON data i ...

Provide the status code along with a custom message when using fileFilter with multer

Is it possible to create a filter for uploaded files using the multer package, where both statusCode and message are returned if wrong files are sent by the user? In my current setup, I am only able to either send a message or a statusCode when validating ...

Validation of VAT numbers using JavaScript instead of PHP

I came across an interesting function at this link that is used for checking VAT numbers in the EU. However, I am struggling to integrate it with my registration form. I would like to convert it into a JavaScript function so that I can validate the number ...

Retrieve information from a URL and transform it into a JSON array

One of my functions looks like this: function retrieveJsonDataFromWebsite(url, callback) { let chunks = []; return require('https').get(url, res => { res.setEncoding('utf8') .on('data', (chunk) => { ...

How can I trigger a save dialog to allow downloading a file in AngularJS?

On the server, I have a directory containing files. When a client sends a file name, I successfully retrieve the file from the server. The response from the server is working fine so far. However, after receiving the response, I want to prompt the user to ...

Is there a way to display the JavaScript widget exclusively on the homepage or main page

How can I limit the display of a Twitter widget on my blog page to only show on the main page and hide it when visitors navigate to sub-pages or individual blog entries? ...

I am experiencing an issue where tapping on the Status Bar in MobileSafari is not functioning correctly on a specific

I am struggling to troubleshoot this problem with no success so far. The HTML5 JavaScript library I'm developing has a test page that can display a large amount of output by piping console.log and exceptions into the DOM for easy inspection on mobile ...

Transforming a CSV document into a JSON format in order to generate a hierarchical tree structure for constructing a D3 categorical tree diagram

I have a CSV file that is structured like this: "","Sequence","Paths","sequence_length" "1","Social -> Social -> Social -> Social -> Social -> Social -> Social -> Social",29,8 "2","Social -> Social -> Social -> Social -> S ...

What is the best way to retrieve data from MySQL for the current month using JavaScript?

I need to retrieve only the records from the current month within a table. Here is the code snippet: let startDate = req.body.startDate let endDate = req.body.endDate let result = await caseRegistration.findByDate({ p ...

What could be the reason for this code returning a "module not found" error?

Within localbase.js... const fs = require("fs"); if(!fs.existsSync(__dirname + "/localbase.json")) fs.writeFileSync("./localbase.json", "{}"); let database = require("./localbase.json"); The code abov ...

show various commands and outcomes of the getElementsByClassName() function

Can someone help me figure out how to use the "getElementsByClassName() Method" in JavaScript to change or display different colors? I am trying to change the background color to blue for the class "ex" and red for the class "example", but it's not wo ...

The colid column type received from the bcp client is not valid

I've been working on an app for a proof of concept. One of the key functionalities involves reading data from a JSON file through an endpoint and then inserting that data in bulk into a database table. However, although the database table is successfu ...

Custom Sizing for Bootstrap Modals

I need assistance with creating a dynamic bootstrap modal that adjusts its width based on the content and includes a vertical scrollbar when needed. Although the vertical scrollbar is functioning correctly, the horizontal width appears to be static. C ...

Using `preventDefault()` does not stop the action from occurring

Whenever I apply event.preventDefault() to a link, it works perfectly fine. But when I do the same for a button, it doesn't seem to have any effect! Check out the DEMO This is the code snippet in question: <a id="link" href="http://www.google.co ...

Using jQuery to swap an image with a div element and then using the image as the

I have a collection of images in a div, like so: <div class="image-container"> <img width="174" height="174" src="http://mysite.com/images/portfolio/p1.jpg" class="image-style" typeof="foaf:Image"> <img width="174" height="174" src= ...

What is the process for extracting data from a canvas tag and why does it appear invisible on my browser?

The highlighted area in this image contains the HTML content and the red circle marks the section to be scraped The phone number can be found within the canvas tag. However, when trying to scrape the tag, it shows "Your browser does not support the HTML5 c ...