Home > database >  CORS Error. cannot access assets folder in parent directory from index.html
CORS Error. cannot access assets folder in parent directory from index.html

Time:12-25

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:[email protected]&family=Work Sans:[email protected]&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 >
      <div >BackpackPacker</div>
      <div >All backpack packing, all the time.</div>
    </header>
    <main ></main>
    <footer >
      <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  id="everyday">
    <figure >
      <img src=${everydayPack.image} alt="" />
    </figure>
    <h1 >${everydayPack.name}</h1>
    <ul >
      <li >Volume:<span> ${
        everydayPack.volume
      }l</span></li>
      <li >Color:<span> ${everydayPack.color}</span></li>
      <li >Age:<span> ${everydayPack.backpackAge()} days old</span></li>
      <li >Number of pockets:<span> ${
        everydayPack.pocketNum
      }</span></li>
      <li >Left strap length:<span> ${
        everydayPack.strapLength.left
      } inches</span></li>
      <li >Right strap length:<span> ${
        everydayPack.strapLength.right
      } inches</span></li>
      <li >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

CodePudding user response:

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.

CodePudding user response:

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"

  • Related