I am trying to import a module to my index.html file.
Here is the code:
// Index.html:
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<title></title>
</head>
<body>
<div></div>
<script type="module" src="module.js"></script>
<script type="text/javascript">
import { addTextToBody } from 'module.js';
addTextToBody('some text here');
</script>
</body>
</html>
And the js:
export function addTextToBody(text) {
const div = document.createElement('div');
div.textContent = text;
document.body.appendChild(div);
}
I am getting these errors:
Uncaught SyntaxError: Unexpected token { - Line 18
Access to Script at 'module.js' from origin 'null' has been blocked by CORS policy: Invalid response. Origin 'null' is therefore not allowed access.
How can I fix this?
I am trying to import a module to my index.html file.
Here is the code:
// Index.html:
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<title></title>
</head>
<body>
<div></div>
<script type="module" src="module.js"></script>
<script type="text/javascript">
import { addTextToBody } from 'module.js';
addTextToBody('some text here');
</script>
</body>
</html>
And the js:
export function addTextToBody(text) {
const div = document.createElement('div');
div.textContent = text;
document.body.appendChild(div);
}
I am getting these errors:
Uncaught SyntaxError: Unexpected token { - Line 18
Access to Script at 'module.js' from origin 'null' has been blocked by CORS policy: Invalid response. Origin 'null' is therefore not allowed access.
How can I fix this?
Share Improve this question asked Sep 15, 2018 at 9:13 user10044012user10044012 1-
3
Use
<script type="module">
even for the inline script – Bergi Commented Sep 15, 2018 at 9:48
2 Answers
Reset to default 6module.js
should be./module.js
- You don't need to import the module at the beginning of the page (but you can).
- Using
import
requires the script to be of typemodule
not just the imported script. - You should place modules imports in
<head>
(at the very beginning).
The following example works (I cut out unessential parts):
<!-- index.html -->
<meta charset="utf-8">
<script type="module">
import { addTextToBody } from './module.js';
addTextToBody('some text here');
</script>
// module.js
export function addTextToBody(text) {
const div = document.createElement('div');
div.textContent = text;
document.body.appendChild(div);
}
The code provided above will work with Firefox, but not with Chrome. It appears you are using Chrome (I assume that from your error message). Chrome strictly forbids access to resources with the file://
protocol. There are a handful solutions:
- Host your code with a webserver (e.g. nginx).
- Use a different webbrowser (e.g. Firefox).
- Disable web security altogether, refer to this answer.
Try:
import { addTextToBody } from './module.js';