0

I just did a simple JavaScript on export/import and inserted it in the html I am having an error "Uncaught SyntaxError: Cannot use import statement outside a module". I did a search on StackOverflow and found that script type must be declared as "module". After adding this, I get an error "class02.html:1 Access to script at 'file:///C:/xxx/yyyyy/animal.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."

Below is my code : animal.js:

export class Animal {
    constructor(type, legs) {
        this.type = type;
        this.legs = legs;
    }
}

class02.html :

<html>
    <head>
        <script type="module">
            import { Animal } from './animal.js';
            let cat = new Animal('Cat', 4);
            cat.legs = 3;
            alert(cat.legs);        
        </script>
    </head>
    <body>
    <h1>test</h1>
    </body>
</html>

Both class02.html and animal.js are in the same directory in my C drive. Can somebody please help me on this.

1 Answer 1

1

To fix CORS error, you need to run html file on a server. You can install apache or nginx on your machine and run your code on it. In my case, I am using Wamp on Windows 10 and moved it to the www folder. It worked as well.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.