Incorporate a custom style sheet into your Express application

Utilizing ejs, express, and parse.com for my web application backend has presented a challenge when it comes to adding stylesheets. Despite searching for solutions, I have not been able to resolve the issue. Sharing my code in hopes of finding a solution.

Displayed below is an excerpt from cloud/app.js:

var express = require('express');
var app = express();

app.use(express.static(__dirname + '/public'));
app.set('views', 'cloud/views');  // Specify the folder to find templates
app.set('view engine', 'ejs');    // Set the template engine
app.use(express.bodyParser());    // Middleware for reading request body

var Movies = Parse.Object.extend('Movies');

app.get('/', function(req, res) {

    var query = new Parse.Query(Movies);
    query.find({

        success: function(results) {
            res.render('movie-list', { movies: results });
        },

        error: function(results, error) {

        }

    });
});


app.listen();

In addition, here is the template located in the views directory:

<html>
    <head>
        <title>Movies</title>
        <link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.2/css/bootstrap.min.css" rel="stylesheet">
        <link href="css/style.css" type="text/css">
    </head>
    <body>
        <h1>Movies</h1>
        <ul id="categoryList" class="list-group">

            <%
                for (var i = 0; i < movies.length; i++)
                { 
                    var movie = movies[i];
            %>

            <li class="list-group-item"><%= movie.get('Movie')%></li>

            <%
                }
            %>

        </ul>

    </body>
</html>

Your assistance on this matter would be highly appreciated. Many thanks!

Answer №1

I found a solution to my own query and made a change by removing a line of code:

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

Instead, I kept the link to the stylesheet in the header of my template intact:

<link href="/css/style.css" type="text/css">

Now everything is working perfectly with my stylesheet.

Answer №2

Although I haven't had the chance to test your code, a quick look at my Parse web apps reveals that my stylesheets links begin with /

Perhaps consider making this change:

<link href="css/style.css" type="text/css">

to:

<link href="/css/style.css" type="text/css">

Best of luck!

Answer №3

Incorporate the following code snippet into your app.js:

var path = require('path');
app.use('/css',express.static(path.join(__dirname, 'public/css')));

Now, when referencing your css file, use:

<link href="css/style.css" rel="stylesheet">
. This should properly link your CSS stylesheet to your application.

Understanding the express static middleware and why it's important to include these lines is crucial for effective application development. The express.static middleware serves the static assets of an Express application in the following ways:

  • Serve static content for the app from the "public" directory within the application directory

    // GET /style.css, etc. app.use(express.static(__dirname + '/public'));

  • Mount the middleware at "/static" to serve static content only when their request path is prefixed with "/static"

    // GET /static/style.css, etc.

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

  • Serve static files from multiple directories while prioritizing "./public" over others

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

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

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

These are three distinct methods for utilizing the express static middleware effectively within your application.

Answer №4

When utilizing the express generator (npm install express-generator -g), don't forget to include your styles in the /public/stylesheets/style.scss files

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 is the reason for an event triggering on a parent element before its child element when using a descendant selector?

I encountered a strange issue in my code where the event on a parent element seemed to trigger before the event on its child, rendering my e.stopPropagation() ineffective. Demo: $(document).ready(function() { // Directly binding events to the elemen ...

Creating a new array in Vue.js by filtering the results of a promise iteration

Is there a way to use the splice method to insert promise values from an old array into a new one for vue reactivity? I'm encountering an issue where the newArray remains empty and does not receive any values. Check out this link for more information. ...

The JSON response did not contain the expected property in Javascript

Currently, I am developing a weather widget using React that displays temperature and rain forecast. The data is fetched from OpenWeather API and the JSON response structure is as follows: //rainy day 0:{ main: { temp:10} rain: { 3h: 1000} } / ...

Idea fails to detect imports

I have been attempting to use Angular2 in IntelliJ IDEA IDE. Although my code is valid (I have tried compiling and executing it), the IDE keeps showing me this error: https://i.stack.imgur.com/w6wIj.jpg Is there a way to configure IntelliJ IDEA to hide t ...

What is the best way to change a JavaScript variable into a PHP variable?

I am interested in converting my JavaScript variable to a PHP variable... Currently, I have the following scenario - in the code below there is a variable e, but I would like to utilize e in PHP as $e: <script> function test() { var e = documen ...

Issue with Firebase functions unexpected CORS error (unhandled promise rejection/CORS)

I'm experiencing a strange issue with Firebase functions that seems to be specific to mobile devices and only occurs immediately after a user logs in for the first time (refreshing the page resolves the issue). Here is the code snippet: const functio ...

Issue with swal() not triggering in Internet Explorer 11

Looking for some assistance here, I believe I might be missing a small detail. The _layout.cshtml file includes all the necessary scripts to ensure that sweetheart works on IE: (this used to work in previous versions, but we haven't had to support I ...

Encountering a "product is not a constructor" error when conducting API testing in Postman

Currently, I am developing a REST API using Node.js, Express, and MongoDB with the help of Mongoose. The testing phase is being done using Postman. However, when I make a POST request to the products endpoint, I encounter an error message stating "Product ...

How can I properly connect my Facebook profile to my current account when utilizing JWT authentication?

I have extensively researched themes, but I am struggling to find a seamless way to connect an existing local strategy account with a Facebook strategy account. The issue lies in the fact that I am using JWT authorization. When a user clicks on the "Conne ...

What is the method for retrieving all 'name' values within a JSON array?

I am currently working on a project using Angular and I have a JSON file. I need to extract all the 'name' values from the array. Ideally, the output should look something like this: ['Sony', 'Apple', 'Sony'] JSON: ...

Is there a way to pull information from a string and organize it into a two-dimensional array?

Utilizing the axios library, I am pulling data from a website. Unfortunately, the data being fetched is in HTML format. The extracted data looks like this: 1 Agartala VEAT 120830Z 23004KT 5000 HZ SCT018 SCT025 34/27 Q1004 NOSIG= 2 Ahmedabad VAAH 120830Z 23 ...

React useEffect appended script not activating

I'm having trouble loading a script that should generate an iframe and display a weather widget upon trigger. I am able to append the script correctly, but it doesn't seem to be called and does not create the iframe. Even when I directly add the ...

Unable to modify the appearance of an HTML element when injected via a Chrome extension

I am currently developing a unique chrome extension that uses Ajax to inject custom HTML into the current tab. This extension appends a <div> element to the body, and now I need to manipulate it using JavaScript. Specifically, I want it to dynamical ...

Identifying when a user has inputted incorrect $routeparams

How can I restrict user input to only "id" as a query parameter in the URL? $scope.$on('$routeUpdate', function () { var id = $routeParams.id //check if user has entered any params other than "id". //if yes do someting }); I want ...

Using Javascript libraries on a Chromebook: A comprehensive guide to getting started

Doing some coding on my chromebook and wondering if it's possible to download and utilize libraries such as jQuery. Would really appreciate any assistance with this! ...

Mocking in AngularJS: Utilizing the same service with varied functions for unit testing with Jasmine

Exploring a new service, Service A, with various functionalities: The snippet of application code is as follows: angular.module('app').factory('ServiceA', function() { var ServiceA = { _retryItem: null, retryItem: ...

Unable to set a value for the variable

const readline = require('readline'); let favoriteFood; const rl = readline.createInterface(process.stdin, process.stdout); rl.question('What is your favorite food?', function(answer) { console.log('Oh, so your favorite food is &a ...

Tips for looping through client.get from the Twitter API with node.js and express

I am in the process of developing an application that can download a specific number of tweets. For this project, I am utilizing node.js and express() within my server.js file. To retrieve data from the Twitter API, I have set up a route app.get('/ap ...

Adjust ChartJS yAxes "tick marks"

I'm having trouble adjusting the scales on my yAxes and all the information I find seems to be outdated. My goal is to set my yAxes range from 0 to 100 with steps of 25. Check out this link yAxes: [ { ...

Utilizing Angular to intercept AJAX requests, verifying internet connectivity before proceeding with sending the request

In my Angular (with Ionic) app, I have this code snippet: my_app.factory('connectivityInterceptorService', ['$q', '$rootScope', function ($q, $rootScope) { var connectivityInterceptorServiceFactory = {}; var _request ...