Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

"access to script from origin 'null' has been blocked by CORS policy" error while trying to launch an html page using an imported js function

I got this error while trying to launch an html page using a javascript file which imported a function from another file:

Access to script at 'file:///C:/Users/bla/Desktop/stuff/practice/jsPractice/funcexecute.js' 
from origin 'null' has been blocked by CORS policy: 
Cross origin requests are only supported for protocol schemes: http, data, chrome, chrome-extension, https.
Failed to load resource: net::ERR_FAILED

Here's the html code:

<!DOCTYPE html>
<html>
<head>
    <meta charset='utf-8'>
    <meta http-equiv='X-UA-Compatible' content='IE=edge'>
    <title>Page Title</title>
    <meta name='viewport' content='width=device-width, initial-scale=1'>

</head>
<body>
    <script type = 'module' src='funcexecute.js'></script>

</body>
</html>

js file which was called from the html: (funcexecute.js)

import sumup from '/funcfile.js';
console.log(sumup(1,2));

Imported module: (funcfile.js)

function sumup(num1, num2){
    return num1+num2;
}
export default sumup;

How can i fix this? (im using vscode)

like image 278
noon Avatar asked Jan 25 '20 19:01

noon


People also ask

How do I fix origin Null has blocked by CORS policy?

From Origin 'null' Has Been Blocked By CORS Policy Error. To fix this error is also easy, what you need to do is to create a local web server, and then upload the Html and JS file to the webserver.

How do I fix access to XMLHttpRequest at origin Null has blocked by CORS policy?

Access to XMLHttpRequest at 'http://127.0.0.1:5000/predict_home_price' from origin 'null' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource. You need to add CORS headers to the response coming back from wherever url is pointing to.


1 Answers

You cannot use a script file as a module without using a server. Take a look here

Here are some of the options

  • Use Live Server (Extension for VS Code)
  • Use http-server module from node (install via npm then run http-server . from your project directory)
  • use http.server package from python
  • use a wamp (or lamp) server

In short cannot use type="module" with file protocol

like image 127
HARDY8118 Avatar answered Sep 18 '22 05:09

HARDY8118