Access to script at ‘file:///xxx.xxx’ from origin ‘null‘ has been blocked by CORS policy .... 解决办法

问题描述

编辑单 HTML 文件,通过 script 引入 JS 代码,JS 使用 ES Module 模块化导出,控制台发生CORS 跨域报错


问题代码

下面展示简单的代码

 index.html

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Document</title>
  <script src="./index.js" type="module"></script>
</head>
<body>
  <div>
    <input type="file">
  </div>
</body>
</html>

index.js

import { captureFrame } from './captureFrame.js';

const inp = document.querySelector('input[type=file]');

inp.onchange = (e) => {
  const file = e.target.files[0];
  const result = captureFrame(file, 1);
};

captureFrame.js

export function captureFrame (videoFile, time = 0) {
  const video = document.createElement('video');
  video.src = URL.createObjectURL(videoFile);
  console.log(video.src);
}

解决方法

之前打开项目是直接在 VSCODE 右键,打开 HTML 文件然后在浏览器访问


解决的办法就是安装一个 Live Serve 插件,然后通过启动插件访问对应的文件

 

 插件默认是 5500 端口


 可以看到使用插件访问之后,JS 正常运行,控制台无报错


文章如有错误,恳请大家提出问题,本人不胜感激 。 不懂的地方可以评论,我都会 一 一 回复

文章对大家有帮助的话,希望大家能动手点赞鼓励,大家未来一起努力 长路漫漫,道阻且长

猜你喜欢

转载自blog.csdn.net/qq_52855464/article/details/140586953