1

I'm learning JavaScript concretely modules and I want to test everything I have learned about modules, but when I'm connecting file it and running it throws an error and I don't understand why.

Here is the error:

enter image description here

Here is the HTML:

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <title>Modules</title>
  </head>
  <body>
    <script type="module" src="script.js"></script>
  </body>
</html>

First JS file:

export const module = {
  one: "one",
  second: "second",
  third: "third"
};

Second JS file:

import {module} from "./modules.js";

console.log(module);

Please say what is wrong and what should I do?

Raghul SK
  • 1,256
  • 5
  • 22
  • 30
  • You must be opening the `.html` file directly in the browser. This would throw the `CORS` error. You could try setting up a local server and serve the whole project directory. You can use `live-server` npm package for creating the server. – rishabh0211 Jul 04 '20 at 06:53
  • This guy seems to have encountered the same error,,, seems like he approved the solution you could also try it https://stackoverflow.com/questions/52919331/access-to-script-at-from-origin-null-has-been-blocked-by-cors-policy – Steve Nginyo Jul 04 '20 at 06:51

1 Answers1

1

It's very clear to show error message in your console.

You should run a web server (e.g. nginx) and put files to correct folder based on server defined to use HTTP request for running it.

EX: Run a simple node.js server

  1. Create package.json and install express package.

package.json

{
  "name": "example",
  "version": "1.0.0",
  "dependencies": {
    "express": "^4.17.1"
  },
  "scripts": {
    "start": "node server.js"
  },
}
  1. Write a very simple server.js file.

server.js

const express = require('express');
const app = express();

app.get("/", (req, res) => {
    res.sendfile(__dirname + '/index.html', err => {
        if (err) res.send(404);
    });
});

app.get(/(.*)\.(js)/i, (req, res) => { // it also can add other filenames extension
    res.sendfile(__dirname + "/" + req.params[0] + "." + req.params[1], err => {
        if (err) res.send(404);
    });
});


app.listen(3000, () => { // port can be modified
    console.log('Listening on port 3000!');
});
  1. Put all your files and the above files in the same folder.

  2. Run npm start or node server.js to launch server.

Alvin
  • 454
  • 3
  • 7