Click here to Skip to main content
14,877,543 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
I've modularised two classes Person and Teacher exactly as shown down below. But when I'm trying to call the Teacher class and use its methods in Index.html, it's generating an error in the console window of Chrome browser saying: "Uncaught SyntaxError: Cannot use import statement outside a module". I'm using Visual Studio Professional 2017 and opening Index.html with Chrome browser. I'm not using Node. Even if Index.html is opened with Firefox it displays the same error with a little different description: "SyntaxError: import declarations may only appear at top level of a module". My codes follow below.

What I have tried:

Person.js

export class Person {
    constructor(name) {
        this.name = name;
    }

    printName() {
        console.log(`My name is ${this.name}.`);
    }
}


Teacher.js

import { Person } from "./Person";

export class Teacher extends Person {
    constructor(name, degree) {
        super(name);
        this.degree = degree;
    }

    printQualification() {
        console.log(`My qualification is ${this.degree}.`);
    }
}


Index.js

import { Teacher } from "./Teacher";
const teacher = new Teacher('MyName', 'MyQualification');
teacher.printName();
teacher.printQualification();


And finally, Index.html

<!DOCTYPE html>

<html lang="en" xmlns="http://www.w3.org/1999/xhtml">
<head>
    <meta charset="utf-8" />
    <title>Object-oriented Programming</title>
</head>
<body>
    <h1>Object-oriented Programming</h1>
    <script src="Index.js"></script>
</body>
</html>


As an alternative, I tried to explicitly define Index.js as a module in Index.html with the following line:

<script type="module" src="Index.js"></script>


But it generates even a bigger error displaying the following two error messages:

"Access to script at 'file:///D:/Pendings/Object-oriented%20Programming_Mosh-Hamedani/Index.js' from origin 'null' has been blocked by CORS policy: Cross origin requests are only supported for protocol schemes: http, data, chrome, chrome-extension, chrome-untrusted, https."

"Failed to load resource: net::ERR_FAILED"

Why is this happening? I've stumbled upon it so badly. Just because of this single factor I can't move ahead with the project. So how do I solve it? I'm new in JavaScript and can't figure out the direction. Please help.
Posted
Updated 3-Feb-21 2:59am

1 solution

UPDATE: New Info
The main point is that you need a web server running so you can run your web app.
There are restrictions on the file:\\\ protocol so you can't just double-click your html file and have it run because the browser knows it is loading the files from a file system and is protecting the user.

Now it is up to you to determine which web server you will install. It is a separate technology from your dev environment. Sometimes Visual Studio will provide a web server for the developer but in your case you are saying you don't see that.

That means you will now have to go out and determine which web server technology you will use. If you're on Windows 10 I saw this thing in the app store : https://www.microsoft.com/en-us/p/easy-web-server/9n10mcd0671v
disclaimer: I'm not affiliated with that software at all and I have no idea if you really want to install it. It is an example for you.
Maybe you could just install that and have it point to your web files then you'd load your files from the web server and you (probably) won't get the CORS error you originally saw.

Otherwise go ahead and install Node (and node will install NPM Node Package Manager) and then follow the instructions to run a Node web server :

Follow these instructions to do that:
https://www.npmjs.com/package/http-server

That one will probably be your best one because it will help you in your future development.


###################################################################
The root problem is that it is attempting to access the file via the file protocol and it is not supported via CORS.
'file:///D:/Pendings/Object-orien...


I'm guessing you are examining your page by double-clicking it in the file system and it loads in your browser (which uses the file protocol).

The solution should be to simply run a web server and load the page from the actual server via http.

if you have node and npm you can try:
$ http-server -p 8080


Or in Visual Studio you should be able to "run" the project and iis should load everything up.
   
v2
Comments
priyamtheone 13-Feb-21 7:07am
   
@raddevus: I'm not using Node. I don't have a VS project or solution file which I can "run". There are three JavaScript files and an html file as mentioned above in a folder. I'm using Visual Studio Professional 2017 to open the folder and then opening Index.html by right clicking and selecting "Open with Google Chrome". I suppose, VS Professional 2017 doesn't have the option to download and use Live-Server like VS Code. In this scenario, how do I run a web server and load the page from the actual server via http? Please suggest.
raddevus 13-Feb-21 10:29am
   
I've added new info to my original answer. Hope it helps. :)
priyamtheone 14-Feb-21 8:35am
   
Thanks for the update. I installed node and live-server. Thereafter, this is what I did:

1) In Teacher.js-
import { Person } from "./Person.js";
2) In Index.js-
import { Teacher } from "./Teacher.js";
However, can't rename Index.js to Index.mjs as doing so is jeopardising the JavaScript file and treating it as a simple text file and the codes in it are not being treated as codes but simple text instead.

3) In Index.html-
<script type="module" src="Index.js"></script>
4) In command prompt-
live-server --port=1234 --entry-file=Index.html


Now everything is running fine.
priyamtheone 14-Feb-21 8:47am
   
However, I have a few questions.

1) While trying to open Index.html with "live-server Index.html" in command prompt, though the page is opening but an error is showing in the console saying: 'Failed to load module script: The server responded with a non-JavaScript MIME type of "text/html". Strict MIME type checking is enforced for module scripts per HTML spec.' Why is this happening? Why can't I use the default port of 8080?

2) Why couldn't I rename Index.js to Index.mjs? While doing so why couldn't Visual Studio recognise it as a JavaScript module file and messing up all the internal codes? As per the current JS protocols, .mjs is a special kind of file introduced to signify JavaScript modules. So why can't I use it?

3) After starting a live-server session through command prompt, how can I terminate it without closing the command prompt window? It seems, once the live-server starts, there's no way you can input any command in the command prompt. So how do I exit from it? Please clarify my questions.

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)




CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900