Skip to content
Advertisement

I am getting a 404 error when attempting to load a background-image from CSS. Unsure how to proceed

I have searched through several posts regarding this same issue but none seem to resolve my problem. I am getting this 404 error in my console: index.css:1 GET http://localhost:5500/assets/css/assets/css/Battleship-Wallpaper.jpeg 404 (Not Found) I have the image saved in .jpeg format inside of my CSS folder. I am attempting to link the relative path and set the background image like so: background-image: url('assets/css/Battleship-Wallpaper.jpeg');

I have tried moving the image into different file locations within my project, as well as linking the entire filepath, to no avail. The rest of my CSS is loading just fine, here is how I am linking the CSS to my HTML: <link rel="stylesheet" href="./assets/css/index.css">. My intuition tells me that this is a problem with the server. I did not write the code for it, but I have reviewed it and have not been able to find a culprit.

The following is a snippet of the relevant HTML/CSS/JS server code.

const http = require("http");
const { readFileSync } = require("fs");
const path = require("path");
// Create a server using `http`
const server = http.createServer((req, res) => {
  console.log(`Incoming Request - Method: ${req.method} | URL: ${req.url}`);
  // Process the body of the request
  let reqBody = "";
  req.on("data", (data) => {
    reqBody += data;
  });
  // When the request is finished processing the entire body
  req.on("end", () => {
    // Parsing the body of the request
    if (reqBody) {
      req.body = reqBody
        .split("&")
        .map((keyValuePair) => keyValuePair.split("="))
        .map(([key, value]) => [key, value.replace(/+/g, " ")])
        .map(([key, value]) => [key, decodeURIComponent(value)])
        .reduce((acc, [key, value]) => {
          acc[key] = value;
          return acc;
        }, {});
    }
    // Home Page
    if (req.method === "GET" && req.url === "/") {
      const resBody = readFileSync("./index.html");
      res.statusCode = 200;
      res.setHeader("Content-Type", "text/html");
      res.end(resBody);
      return;
    }
    // Serving Static Assets
    const ext = path.extname(req.url);
    if (req.method === "GET" && ext) {
      try {
        const resBody = readFileSync('.' + req.url);
        res.statusCode = 200;
        if (ext === ".jpg" || ext === ".jpeg") {
          res.setHeader("Content-Type", "image/jpeg");
        } else if (ext === ".css") {
          res.setHeader("Content-Type", "text/css");
        } else if (ext === ".js") {
          res.setHeader("Content-Type", "text/javascript");
        }
        res.end(resBody);
        return;
      } catch {
        console.error(
          "Cannot find asset",
          path.basename(req.url),
          "in assets folder"
        );
      }
    }
    // Page Not Found
    res.statusCode = 404;
    res.setHeader("Content-Type", "text/plain");
    const resBody = "Page Not Found";
    res.write(resBody);
    res.end();
  });
});
// Set the port to 5000
const port = 5000;
// Tell the port to listen for requests on localhost:5000
server.listen(port, () => console.log("Server is running on port", port));
body {
    font-family: 'Orbitron', sans-serif;
    background-image: url('./assets/css/Battleship-Wallpaper.jpeg');
    background-size: cover;

    display: table-cell;
    vertical-align: middle;
}
<!DOCTYPE html>
<html>

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Battleship</title>
    
    <link rel="stylesheet" href="./assets/css/index.css">

    <link rel="preconnect" href="https://fonts.googleapis.com">
    <link rel="preconnect" href="https://fonts.gstatic.com" crossorigin>
    <link href="https://fonts.googleapis.com/css2?family=Orbitron:wght@500&display=swap" rel="stylesheet"> 

    <script type="module" src="./assets/js/index.js"></script>
</head>

<body>
    <center>
    <h1 class="headers">Battleship</h1>
    <h2 class="headers" id="results"></h2>
    <button id="reset">Play Again</button>
    <div id="gameBox"></div>
    </center>
</body>

</html>

In case this has anything to do with my DOM functionality, here is the relevant JS:

import Board from "./board.js";

let board = new Board();

const grid = board.grid;
const gameBox = document.getElementById('gameBox');
const reset = document.getElementById('reset');

const checkPosition = (currButton, currButtonVal) => {
    let currResults = document.getElementById('results');

    if (!currButtonVal) currButton.style.backgroundColor = 'red';

    if (currButtonVal) {
        currButton.innerHTML = currButtonVal;
        currButton.style.backgroundColor = 'green';

        board.numRemaining--;

        if (board.isGameOver()) {
            currResults.innerText = 'You win!';
            gameBox.style.display = 'none';
            reset.style.display = 'block';
        };
    };
};


const populateBoard = (grid) => {
    for (let row = 0; row < grid.length; row++) {
        let currDiv = document.createElement('div');

        currDiv.setAttribute('id', `row-${row}`)
        currDiv.setAttribute('class', 'rows');
        currDiv.style.display = 'flex';

        gameBox.appendChild(currDiv);

        for (let col = 0; col < grid.length; col++) {
            const currButtonVal = board.makeHit(row, col);

            let currButton = document.createElement('button');
            currButton.setAttribute('id', `col-${col}`);
            currButton.setAttribute('class', 'buttons');

            currButton.addEventListener('click', e => {
                if (board.isGameOver()) e.preventDefault();

                checkPosition(currButton, currButtonVal);
                });

            currDiv.appendChild(currButton);
        };
    };
};

window.addEventListener("DOMContentLoaded", () => {
    populateBoard(grid);

    reset.addEventListener("click", () => {
            window.location.reload(true);
    });
});

Any insight would be greatly appreciated.

Advertisement

Answer

If i check your code i see 3 different pathes:

In your entry text you write:

one time css/assets/css…jpeg
and the other one is css/assets/…jpeg

and later on in the code i see it going one folder up with the dot background-image: url(‘./assets/css/Battleship-Wallpaper.jpeg’);

Can you double check if you have a simple typing error?

User contributions licensed under: CC BY-SA
7 People found this is helpful
Advertisement