Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

javascript modules and CORS

I am trying to understand modules in JavaScript but when I try to write a very simple module I get CORS error.I am using bracket as my text editor and the odd part is when I'm using live preview in brackets the code works but when I normally open the .js file I get error.

index.html

<!DOCTYPE html>     <html>     <head>         <title> JS </title>     </head>     <body>         <script type="module">             import {add} from './libA.js';              console.log(add(10,20));         </script>     </body>     </html> 

libA.js

export function add(a,b) {         return a+b ;     } 

*I get this error ->

Access to Script at 'file:///F:/WEB%20DEV/JavaScript/libA.js' from origin `null` has been blocked by CORS policy:  Invalid response.  Origin 'null' is therefore not allowed access. 

(I even tried the latest version of chrome too)

like image 587
Ahmad Reza Avatar asked May 06 '18 08:05

Ahmad Reza


People also ask

What are JavaScript modules?

A module in JavaScript is just a file containing related code. In JavaScript, we use the import and export keywords to share and receive functionalities respectively across different modules. The export keyword is used to make a variable, function, class or object accessible to other modules.

Are there modules in JavaScript?

JavaScript modules allow you to break up your code into separate files. This makes it easier to maintain the code-base. JavaScript modules rely on the import and export statements.

How do ES6 modules work?

A module is nothing more than a chunk of JavaScript code written in a file. By default, variables and functions of a module are not available for use. Variables and functions within a module should be exported so that they can be accessed from within other files. Modules in ES6 work only in strict mode.

Can I use import in JavaScript?

Introduction to the JavaScript import()The import() allows you to dynamically import a module when needed. Here is how the import() works: The import() accepts a module specifier ( moduleSpecifier ) that has the same format as the module specifier used for the import statement.


1 Answers

Many browsers do not allow you to access files on the local filesystem with JavaScript (even if the HTML document is also on the local filesystem).

This extends to loading JavaScript modules.

Install a webserver and use that (with a URL like http://localhost/) for testing.

like image 193
Quentin Avatar answered Sep 21 '22 23:09

Quentin