Issue with HTML and CSS linkage inefficiency

Issue with loading CSS file in HTML.

Checking out my HTML code:

<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8">
    <link rel="stylesheet" type="text/css" href="style.css">
    <script src="https://code.jquery.com/jquery-1.10.2.js"></script>
</head>
<body>
    <h1>TEST</h1>
</body>
</html>

The style.css file is in the same directory as the .html file above.

Here's the content of style.css:

body {
   background: red;     
}

Upon inspecting the Chrome developer tools "Network" tab, the status of style.css shows as "pending".

Any suggestions on how to resolve this? I have already tried disabling AdBlock and clearing cache.

I am using node.js to run the server, not sure if that's relevant...

Take a look at my server.js file:

var http = require("http");

// requests are routed through router file
var router = require("./router.js");

// define port number
port = "8080";

// listen for requests
http.createServer(function (request, response) {
   router.home(request, response);
}).listen(port);

// Server running message
console.log('Server running at http://127.0.0.1:' + port + '/');

Check out the router.js file:

var renderer = require("./renderer.js");
var url = require("url");
var htmlHeader = {'Content-Type': 'text/html'};

function home(request, response) {

    if (request.url === "/") {

        if (request.method.toLowerCase() === "get") {

            response.writeHead(200, htmlHeader);

            renderer.view("header", {}, response);
            renderer.view("footer", {}, response);

            response.end();
        } 
    }
}

module.exports.home = home;

Last but not least, take a look at renderer.js file:

// read [view].html files contents
var fs = require('fs');

// insert values into [view].html file
function mergeValues(values, content) {
    // loop over keys
    for (var key in values) {
        // replace all {{key}} with value from object
        content = content.replace("{{" + key + "}}", values[key]);
    }

    // return merged content
    return content;
}


// handle view passed as argument
function view(templateName, values, response) {

    // find [view].html file in /views/ folder
    var fileContents = fs.readFileSync('./views/' + templateName + '.html', {encoding: "utf8"});

    // insert values into file content
    fileContents = mergeValues(values, fileContents);

    // write out content to response
    response.write(fileContents);
}

module.exports.view = view;

Thank you!

Answer №1

When a web server receives a request for static files like CSS, it may not be able to find the file because there is no specific route defined for it.

To solve this issue, you can include code similar to the following:

if (request.url === "/style.css") {
    fs.readFile('style.css', function (err, data) {
        response.writeHead(200, {'Content-Type': 'text/css', 'Content-Length': data.length});
        response.write(data);
        response.end();
    });
}

There are more efficient ways to serve static files using modules that automatically locate existing files for you. The provided code snippet is just a simple solution.

Answer №2

Do you have permission to modify the CSS file? You can try the following command:

chmod 777 style.css

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

Can you please provide the origin of the ACL parsing?

I recently came across the parse server, and while reviewing the spec I noticed a mention of certain methods: equal(object.getACL().getReadAccess(user), true); equal(object.getACL().getWriteAccess(user), true); equal(object.getACL( ...

How to conceal hyperlink underline with css

This is some HTML Code I'm working with <a href="test.html"> <div class=" menubox mcolor1"> <h3>go to test page</h3> </div> </a> Here's the corresponding CSS: .menubox { height: 150px; width: 100%; ...

Having trouble running a React application from GitHub on VS Code

Sorry for the beginner question. I recently downloaded a React application from GitHub. However, when I attempt to run it locally on VS Code, I encounter some dependency errors. Here are the dependencies listed in the JSON file: "dependencies": { ...

Switch the appearance between two elements

In my HTML table, I have different levels of content - from main "contents" to nested "sub-contents" and even deeper "sub-sub-content". My goal is to hide all sub-content within the content cell that I click on. <table> <tr class=' ...

Align text in the center of a static container

I am facing the challenge of aligning four h4 tags in the center of their respective fixed divs, all set to width: 100% to ensure their background-color: rgba(255, 255, 255, 0.5); covers the entire browser width. Despite trying various combinations of CSS ...

Confirm that there are no errors thrown while utilizing the async version in Checkit

After experimenting with the example provided in the GitHub repository for checkit, I encountered an interesting issue. When I executed it on Node.js 6.2.2 using the async version, it did not throw an error as expected. var checkit = new Checkit({ first ...

Is it possible to delete browsing history in Express using node.js?

Upon user login, I store user information in browser sessions on the client side (using Angular) like this: $window.sessionStorage.setItem('loggedInUser', JSON.stringify(val)); For logout authentication on the backend (using Passportjs), I have ...

Exploring Text Color Verification with CSS in Selenium IDE

I am working on a project and want to ensure that my link is styled properly: <a class="title">My link</a> The CSS code used to style my link is as follows: a.title { color: #CC3333; } How can I confirm that the text "My link" is displayi ...

Instructions for converting a readonly text field into an editable one using JavaScript

I'm trying to make it so that when the button (with id name_button) is clicked, the text field (with id name_text_field) becomes enabled. However, my current code doesn't seem to be working. Here's a snippet of my HTML: <input type="tex ...

Use jQuery to add an anchor tag before an image and then close the anchor tag

Here is the code snippet I am working with: <div id="slider"> <img src="images/p1.jpg" /> <img src="images/p2.jpg" /> <img src="images/p3.jpg" /> </div> I am looking to dynamically add <a> tags before ...

Is there a way to create a dynamic associative array using jquery?

I am looking to create an array structured like the following:- arr[0][from] = value arr[0][to] = value arr[1][from] = value arr[1][to] = value . . And so forth. I have input array html elements for the from & to fields. <input type="text" name ...

Creating a border for a checkbox using CSS

I need help with styling a checkbox using jQuery $("#reg_checkbox").css("border","thin solid red"); The border displays correctly in Internet Explorer, but not in Mozilla. How can I ensure browser compatibility for this styling? ...

Currently in the process of configuring an ionic project, encountering a series of errors upon executing the npm install command

gyp ERR! configure error gyp ERR! stack Error: Unable to locate Python executable "python", please set the PYTHON environment variable. gyp ERR! stack at PythonFinder.failNoPython (C:\Program Files\nodejs\node_modules\npm\node_ ...

How to Send a Text Body Using SuperAgent in Node.js Mocha Tests Instead of JSON?

I am currently utilizing SuperAgent to carry out tests on a Node/Express REST API. When using .send, the body content automatically converts to JSON. However, I only want to send plain text. Here is an example: request.post('localhost:3000/api/compi ...

The autocomplete feature in the hotel name field is designed to recognize HTML-encoded entities, thanks to the combination of

I keep encountering this issue. "King & Grove Hotel" is displaying as "King &amp; Grove Hotel" This problem arises while using jQuery autocomplete. ...

Having trouble capturing errors globally from inversify-express-utils controllers

Utilizing the package https://github.com/inversify/inversify-express-utils in my nodejs application has been quite helpful. However, I am facing a challenge in handling errors from any controller. My current approach involves utilizing the express error ha ...

Support control characters when using util.inspect or console.log

Having trouble with a callback error: return cb({code, message: `The command could not be executed: "${chalk.bold(cmd)}".`}, result); The error is being handled like this: if (err) { console.error(err); process.exit(1); } Resulting in control ch ...

Error message in node.bcrypt.js: 'No callback function provided; result is undefined.'

Currently, I am enrolled in Mosh Hamdani's Mastering React Course and have encountered some challenges with back-end development. The most recent issue is an error message stating: “undefined No callback function was given” when attempting to regi ...

Resizing SVG to specify width in pixels and automatically adjust height

I'm having trouble understanding how SVG works. Can someone explain where my mistake is? Here's an example of my inline SVG code: <div style="width:1000px; height:auto; background-color:blue;"> <svg class="_image"><use xlink ...

"Deploy" (execute) historic http handler within Hapi.js

After giving a Node.js meetup presentation, I found myself unable to answer one particular question, and it has been weighing on my mind ever since. Imagine you have a legacy http application or an Express.js application in the form of a function like thi ...