Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
252 views
in Technique[技术] by (71.8m points)

javascript - Importing script with type=module from local folder causes a CORS issue

I have a little html file that calls a javascript file, but when I'm trying to access it in the browser I'm getting the following error:

Access to script at 'file:///C:/Users/jekob/Desktop/battleship/index.js' from origin 'null' has been blocked by CORS policy: Cross origin requests are only supported for protocol schemes: http, data, chrome-extension, edge, https, chrome-untrusted.

I've googled that for hours and found out that I can host my app by a server (like node.js) and then to allow CORS. However I don't want any server. I want just a simple html and a js file.

index.html:

<!DOCTYPE html>
<html>
<head>
    <title>battle-ship</title>
    <link rel="stylesheet" type="text/css" href="index.css">
    
</head>
<body>
<div id="board"></div>
<script type="module"  src="index.js"></script>
</body>
</html>

index.js:

import {board} from './board_0.1.js';

console.log(board);

board.js:

class cell{
    constructor(){
        this.locationByLetter = null;
        this.locationByNumb = [];
        this.occupied = false;
        this.clicked = false;
    }
}

class shipDitel{
    constructor(name,size){
        this.name = name;
        this.size = size;
        this.location =[];
    }
}

export const board = buildBoard();
const shipType = [["Destroyer",2/*size*/],["Submarine",3],["Cruiser",3,],
                  ["Battleship",4,],["AircraftCarrier",5]];

var shipsArr=setShip();
var selectedShip =  selectShip(shipsArr[4]);
var stateGame ={
    setting:true,
    gameIsStart:false
    }

function buildBoard(){
..
};

function setShip(){   //setting to a ship  his name and size .
...
};

function selectShip(ship){
    ...
}

function  onSelectedCell(cell){
    ...
};    

function checkTheZone(cell){  
...
};
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

I've googled that for hours and found out that I can host my app by a server (like node.js)

Yes

and then to allow CORS.

Since it will be Same Origin, you won't need CORS.

However I don't want any server. I want just a simple html and a js file.

Then you can't use browser-side ES6 modules.

You'll need to either write the code to not use modules in the first place, or use something like Webpack or Rollup to convert the code to not use modules afterwards.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...