0

I am learning JavaScript from the course (JavaScript Essential Training) by Morten Rand-Hendriksen. I downloaded all the exercise files and Using Firefox and VSCode and Live Server running locally, I tried to load the example code below (example 5.02) in the browser.

It does not display the CSS style showing the picture of the backpack. In the console, I get this error:

The resource from “http://127.0.0.1:5500/assets/style.css” was blocked due to MIME type (“text/html”) mismatch (X-Content-Type-Options: nosniff).

I set Tracking Content to Off in Settings (see screenshot) but it did not help.

I verified that the file is present "..\assets\images\everyday.svg"

Update: I tried to load it directly in Firefox, not LiveServer. I see in the console, Cross-Origin Request Blocked: The Same Origin Policy disallows reading the remote resource at file:///C:/Users/Me/Documents/Learn/JS/05_03/Backpack.js. (Reason: CORS request not http).

Actual result

actual result

Expected Result:

expected result

The code is here:

index.html

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>BackpackPacker</title>
    <link
      href="https://fonts.googleapis.com/css2?family=Oswald:wght@200..700&family=Work+Sans:wght@100..900&display=swap"
      rel="stylesheet"
    />
    <link
      rel="stylesheet"
      href="../assets/style.css"
      type="text/css"
      media="all"
    />
    <script type="module" src="Backpack.js"></script>
    <script type="module" src="script.js"></script>
  </head>
  <body>
    <header class="siteheader">
      <div class="site-title">BackpackPacker</div>
      <div class="site-description">All backpack packing, all the time.</div>
    </header>
    <main class="maincontent"></main>
    <footer class="sitefooter">
      <p>
        Demo project for JavaScript Essential Training, a LinkedIn Learning
        course.
      </p>
    </footer>
  </body>
</html>

Backpack.js

class Backpack {
  constructor(
    name,
    volume,
    color,
    pocketNum,
    strapLengthL,
    strapLengthR,
    lidOpen,
    dateAcquired,
    image
  ) {
    this.name = name;
    this.volume = volume;
    this.color = color;
    this.pocketNum = pocketNum;
    this.strapLength = {
      left: strapLengthL,
      right: strapLengthR,
    };
    this.lidOpen = lidOpen;
    this.dateAcquired = dateAcquired;
    this.image = image;
  }
  toggleLid(lidStatus) {
    this.lidOpen = lidStatus;
  }
  newStrapLength(lengthLeft, lengthRight) {
    this.strapLength.left = lengthLeft;
    this.strapLength.right = lengthRight;
  }
  backpackAge() {
    let now = new Date();
    let acquired = new Date(this.dateAcquired);
    let elapsed = now - acquired; // elapsed time in milliseconds
    let daysSinceAcquired = Math.floor(elapsed / (1000 * 3600 * 24));
    return daysSinceAcquired;
  }
}

export default Backpack;

script.js

/**
 * Traverse the DOM tree using querySelector() and querySelectorAll()
 * @link https://developer.mozilla.org/en-US/docs/Web/API/Element/querySelector
 * @link https://developer.mozilla.org/en-US/docs/Web/API/Element/querySelectorAll
 */

import Backpack from "./Backpack.js";

const everydayPack = new Backpack(
  "Everyday Backpack",
  30,
  "grey",
  15,
  26,
  26,
  false,
  "December 5, 2018 15:00:00 PST",
  "../assets/images/everyday.svg"
);

const main = document.querySelector(".maincontent");

const content = `
  <article class="backpack" id="everyday">
    <figure class="backpack__image">
      <img src=${everydayPack.image} alt="" />
    </figure>
    <h1 class="backpack__name">${everydayPack.name}</h1>
    <ul class="backpack__features">
      <li class="backpack__volume">Volume:<span> ${
        everydayPack.volume
      }l</span></li>
      <li class="backpack__color">Color:<span> ${everydayPack.color}</span></li>
      <li class="backpack__age">Age:<span> ${everydayPack.backpackAge()} days old</span></li>
      <li class="backpack__pockets">Number of pockets:<span> ${
        everydayPack.pocketNum
      }</span></li>
      <li class="backpack__strap">Left strap length:<span> ${
        everydayPack.strapLength.left
      } inches</span></li>
      <li class="backpack__strap">Right strap length:<span> ${
        everydayPack.strapLength.right
      } inches</span></li>
      <li class="backpack__lid">Lid status:<span> ${
        everydayPack.lidOpen
      }</span></li>
    </ul>
  </article>
`;

main.innerHTML = content;

CSS file in ../assets/style.css

body {
  margin: 0;
  font-family: "Work Sans", sans-serif;
  font-size: 1.6rem;
}

h1,
h2,
h3,
h4,
h5,
h6 {
  font-family: "Oswald", sans-serif;
}

figure {
  margin: 0;
}

.siteheader {
  display: flex;
  flex-direction: column;
  align-items: center;
  padding: 2rem;
}

.site-title {
  margin-top: 1rem;
  margin-bottom: 1rem;
  font-family: "Oswald", sans-serif;
  font-size: 5rem;
  font-weight: 200;
}

.siteheader:after {
  display: block;
  margin: 4rem 0;
  content: "⚍⚌⚍";
}

.maincontent {
  margin: 0 auto;
  padding: 0 1rem;
  max-width: 60rem;
}

.page-header {
  margin-bottom: 3rem;
}

.page-header__heading {
  margin-top: -1rem;
  text-align: center;
}

.page-header:after {
  margin: 4rem auto;
  display: block;
  content: "";
  border-bottom: 3px solid black;
  width: 4rem;
}

.backpack {
  margin-bottom: 4rem;
  /* padding-bottom: rem; */
  display: grid;
  grid-template-columns: 1fr 1fr;
  grid-template-rows: auto 1fr;
  gap: 0 3rem;
}

.backpack:after {
  margin: 0 auto;
  padding-top: 4rem;
  display: block;
  grid-column: span 2;
  content: "";
  border-bottom: 3px solid black;
  width: 4rem;
}

.backpack__image {
  grid-row: span 2;
}

.backpack__name {
  margin-top: 2rem;
  margin-bottom: 0;
  padding-bottom: 2rem;
  font-size: 5rem;
  line-height: 1;
  text-transform: uppercase;
  border-bottom: 3px solid black;
}

.backpack__features {
  margin: 0;
  padding: 2rem 0 0 0;
  list-style-type: none;
}

.backpack__features li {
  padding: 0.2rem 0;
}

/* Subgrid. See https://developer.mozilla.org/en-US/docs/Web/CSS/CSS_Grid_Layout/Subgrid */
@supports (grid-template-columns: subgrid) {
  .backpack__features {
    display: grid;
    grid-template-columns: auto 1fr;
    gap: 0 1rem;
  }

  .backpack__features li {
    display: grid;
    grid-column: span 2;
    grid-template-columns: subgrid;
  }
}

.lid-toggle {
  display: inline-block;
  border: 3px solid black;
  border-radius: 0.3rem;
  padding: 2rem;
  font-size: 1.6rem;
  cursor: pointer;
  background-color: white;
}
.lid-toggle:hover,
.lid-toggle:focus {
  background-color: hsl(0, 0%, 95%);
}

.lid-toggle:active {
  background-color: black;
  color: white;
}

.sitefooter {
  margin-top: 8rem;
  padding: 2rem;
  display: flex;
  justify-content: center;
  background: black;
  color: white;
}

tracking set to off in Settings

likejudo
  • 3,396
  • 6
  • 52
  • 107
  • Have you tried anything from [this post](https://stackoverflow.com/questions/40728554/resource-blocked-due-to-mime-type-mismatch-x-content-type-options-nosniff)? – gbac Dec 20 '21 at 02:12
  • @gbac Yes, I checked that the file is present "..\assets\images\everyday.svg" – likejudo Dec 20 '21 at 02:20
  • 1
    The error is pointing to your css file. – gbac Dec 20 '21 at 02:43
  • @gbac the css file is present in ../assets/style.css I edited the question to show the css file. – likejudo Dec 20 '21 at 03:08
  • 1
    To troubleshoot further, try moving the css file into the same directory as your html file, and then change the href path to `"style.css"` – gbac Dec 20 '21 at 03:27
  • @gbac now it works! but why cannot it see a file in `../assets` Is it something in FireFox? – likejudo Dec 20 '21 at 13:40
  • Since that works, it seems that something is off in your file hierarchy compared to your original href path. Hard to give you the exact solution, since I don't know how your files are set up. However, [this post](https://stackoverflow.com/questions/7591240/what-does-dot-slash-refer-to-in-terms-of-an-html-file-path-location) may help you to get it right. Your css file will definitely work in the assets folder, you just have to make sure that the href pointing to the file is correct. Would you like me to post this as an answer so that your question doesn't remain unanswered? – gbac Dec 21 '21 at 04:04
  • @gbac yes, please post as an answer. But the issue persists with other examples. For instance, with example 5.04. Same issue. The hrefs are correct. I wonder if Firefox or Windows 11 has a security restriction not allowing access to parent directory `..\\` – likejudo Dec 22 '21 at 20:32
  • @gbac when I type `..\assets\style.css` in the Windows File Explorer address bar, it opens the css file correctly. This tells me the href is correct. – likejudo Dec 22 '21 at 20:47
  • I tried to load it directly in Firefox, not LiveServer. I see in the console, `Cross-Origin Request Blocked: The Same Origin Policy disallows reading the remote resource at file:///C:/Users/Me/Documents/Learn/JS/05_03/Backpack.js. (Reason: CORS request not http).` – likejudo Dec 22 '21 at 21:12
  • @gbac I changed the title – likejudo Dec 22 '21 at 21:26

2 Answers2

2

If you're getting CORS error, and you are accessing your site locally (via filesystem, or Live Server) this error typically means that there is something wrong with your href path, src path, or with your file hierarchy. If you are using a node server, then this answer is probably not for you.

Filesystem and Live Server handle parent directories differently.

Live Server uses your opened folder (in VS Code) as the root, and does not let you go to parent directories above that.

Let's say that the folder that you open in VS Code contains only your index.html file, and your assets folder is in it's parent directory.

In this case, Live Server will not let you access the files in your assets folder.

Typically, ../ takes you to the parent directory, but in Live Server, if you are already set in the 'root' directory (the folder that is open in VS Code), then ../ will not take you anywhere.

This is different from your local filesystem, where ../ will take you up as many parent directories as you wish, until you reach the root drive.

What I suggest:

Keep your file hierarchy as simple as possible.

Have your index.html in the root folder for your project, and then keep your assets in subfolders, rather than parent directories.

  • Project Folder

Contains index.html and your assets folder

  • Assets Folder

Contains script.js and style.css

Then, in your html file, change your paths to assets/style.css and assets/script.js

This will allow your site to work for both Live Server and your local Filesystem. It will also make things easier when deploying your website online.

EDIT: Whatever folder you open in VS Code will be your root directory, and Live Server will let you access the files from there and all sub directories. If you are unable to move your assets to the project directory, then make sure you open the folder that contains your assets folder in VS Code. Then navigate to your html file and start the Live Server from there.

gbac
  • 235
  • 3
  • 12
  • upvoted and thank you, but it does not solve my issue. There are several index.html each in a sub folder and they need to share the assets folder. I am trying to open this index.html in live server. In VSCode, I am trying to set multi root folder for live server but it still does not work. – likejudo Dec 23 '21 at 16:20
  • I added an edit to my answer for your use case – gbac Dec 23 '21 at 16:51
  • please see the solution below – likejudo Dec 24 '21 at 11:30
  • Adding that line in `settings.json` doesn't change anything, since `./` points to the current directory, which is already the root by default. The rest of your solution is exactly what I explained in my edit. – gbac Dec 24 '21 at 11:48
  • ok, I did not understand what you had written here [gbac] "make sure you open the folder that contains your assets folder in VS Code. Then navigate to your html file and start the Live Server from there." – likejudo Dec 24 '21 at 15:42
  • ""make sure you open the folder that contains your assets folder in VS Code. " Isn't that different in effect from "add folder to workspace"? – likejudo Dec 24 '21 at 16:16
  • In regards to the functionality of Live Server, they are the same. – gbac Dec 25 '21 at 04:02
  • 1
    ok, I have accepted your answer - Merry Christmas! – likejudo Dec 25 '21 at 14:51
0

Note: see alternative solution at the end.

After a lot of searching, I found this is a VSCode feature for LiveServer. In the JS folder which contains the sub-folders, I saw there is a .vscode folder which contains a file settings.json. In the file, I added the line for root location. So my Settings file looks like this.

settings.json

{
    "editor.formatOnSave": true,
    "editor.defaultFormatter": "esbenp.prettier-vscode",
    "liveServer.settings.root": "./"
}

In VSCode, under File menu, I selected "Add Folder To Workspace" and added the JS folder

add folder to workspace

Now when I open VSCode, I click the poorly chosen icon that is normally used for "copy" and it opens up VSCode Explorer.

vscode

So all I have to do now is to open index.html in whichever subfolder and right-click and choose "Open in LiveServer"

Alterative Solution:

  1. In VSCode choose Open Folder in the File menu

In VSCode choose Open Folder in the File menu

  1. In VSCode, lower right corner (assuming Live Server extension was installed), click "Go Live".

click Go Live

  1. you will see a directory listing; now you can go into a subfolder and open its index.html

list directory

You will find that assets are automatically available.

click index.html

likejudo
  • 3,396
  • 6
  • 52
  • 107