Why is my h1 tag not changing with css

Question:Why is my h1 tag not changing with css


Repl link:https://replit.com/@Residual2023528/Web?s=app

Your path is wrong. Take 1 dot away from the ref:

<link href="../styles/style.css" rel="stylesheet" type="text/css" />
1 Like

I changed it to ../ , but nothing happened

Oh, the index.js is only serving the HTML. You have to add a clause in your server code to serve CSS files as well.

In your index.js file:

const http = require("http");
const fs = require("fs");
const path = require('path');  // Add this

Change this:

const sendResponse = (filename, statusCode, response) => {
  fs.readFile(`./${filename}`, (error, data) => {  // Right here

Add this line too:

if (error) {
      response.statusCode = 500;
      response.setHeader("Content-Type", "text/plain");
      response.end("抱歉,內部錯誤。");
    } else {
      const ext = path.extname(filename);  // Add this

And change the response too:

if (url === "/") {
      sendResponse(`web/index${selector}.html`, 200, response);  // Change here
    } else if (url === "/about.html") {
      sendResponse(`web/about${selector}.html`, 200, response);  // Update this
    } else if (url.endsWith(".css")) {  // Add this
      sendResponse(url.slice(1), 200, response);
    } else {
      sendResponse(`web/404${selector}.html`, 404, response);  // Update this
    }
2 Likes

It seems that some brackets are missing, and then I would like to ask what the following else if (url.endsWith(".css")) { // Add this sendResponse(url.slice(1), 200, response); } else { sendResponse(`web/404${selector}.html`, 404, response); // Update this } means

You hardcoded to serve only the web folder.
The modification to sendResponse allows it to serve files from both the web and styles directories. If you left hard-coded to the web directory, it would not be able to server your css files (since they are in another folder)

Then why does it need to be changed to this? Doesn’t he need to read the html files in the web folder?

The change allows the sendResponse function to serve files from any directory, not just from the web directory. Since your css file is in another directory you need to read all directories in your project. That’s why you have to change the clauses.

Breaking down the change:

  1. When you call sendResponse in your server, you will now include the directory path in the filename argument. For example, when serving your main page, you call sendResponse('web/index.html', 200, response).
  2. And now inside the sendResponse function, the fs.readFile() function now reads the file at the location ‘./’ + filename. And since filename includes the directory path (not a specific path like the Web folder or the Styles folder), this means it can correctly find files in either the web or styles directories.
2 Likes

This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.