Chrome CORS-资源动态负载跨源错误

w1e3prcc  于 12个月前  发布在  Go
关注(0)|答案(1)|浏览(72)

我面对错误:

TypeError: Failed to resolve module specifier '../static/myJson.json'. 
The base URL is about:blank because import() is called from a CORS-cross-origin script.

在运行时,当页面加载到浏览器中并试图动态地import一个json文件。
这段代码:

// myCode.ts
export const MY_JSON_FILEPATH = "";

window.addEventListener("load", async () => {
  try {
    const myData = await import(MY_JSON_FILEPATH); // replaced by rollup-replace
  } catch (error) {
    console.warn(`Unable to load json file`, error);
    return;
  }
}

它由html模板加载:

#index.html
<!DOCTYPE html>
<html>
    <head>
        <meta
            name="viewport"
            content="width=device-width, initial-scale=1, user-scalable=no"
            charset="UTF-8"
        />
        <script src="myCode.js"></script>
    </head>
    <body>
    </body>
</html>

当我从另一个静态导入JSON的源文件中做同样的事情时,一切都很好,没有CORS问题。但是,由于我将其更改为使用rollup来尝试在运行时动态加载资源文件,因此我面临此错误。
我把整个设置都贴出来了,以防我错过了什么。我不知道这个CORS从哪里来。
使用:

"typescript": "^4.6.3"
"rollup": "^2.60.2",
"rollup-plugin-typescript2": "^0.31.2",
"rollup-plugin-replace": "^2.2.0",
"rollup-plugin-commonjs": "^10.1.0",

Typescript设置为:

{
  "compilerOptions": {
    "lib": [
      "dom",
      "es6"
    ],
    "target": "es6",
    "outDir": "./dist",
    "rootDirs": ["./src",  "../../../config/*.json"],
    "module": "ESNext",
    "declaration": true,
    "strict": true,
    "moduleResolution": "node",
    "esModuleInterop": true,
    "resolveJsonModule": true,
  },
  "include": ["./src/**/*.ts"],
  "exclude": ["node_modules", "dist"]
}

汇总:

import commonjs from "@rollup/plugin-commonjs";
import json from "@rollup/plugin-json";
import replace from "@rollup/plugin-replace";
import typescript from "rollup-plugin-typescript2";
import { nodeResolve } from "@rollup/plugin-node-resolve";
import { createBasicConfig } from "@open-wc/building-rollup";
import merge from "deepmerge";
import path from "path";

const pathResolve = (loc) => path.resolve(__dirname, loc);
const externalJsonFile = path.resolve("./static/myJson.json");

const nodeModules = "node_modules/**";

const baseConfig = createBasicConfig();

export default merge(baseConfig, [
    {
        input: pathResolve("src/index.ts"),
        output: [
            {
                file: pathResolve("dist/index.es.js"),
                format: "esm",
            },
            {
                file: pathResolve("dist/index.js"),
                format: "cjs",
            },
        ],
        external: [externalJsonFile],
        plugins: [
            nodeResolve([".ts"], { browser: true }),
            typescript(),
            replace({
                MY_JSON_FILEPATH: `"${externalJsonFile}"`,
            }),
            commonjs({
                include: nodeModules,
                extensions: [".js", ".ts", ".mjs", ".json"],
            }),
        ],
        context: "window",
    },
}
qij5mzcb

qij5mzcb1#

在浏览器中直接使用“file://”协议访问文件时,可能会遇到CORS(跨域资源共享)错误。发生此错误的原因是浏览器强制执行同源策略,该策略限制通过“file://”协议加载的资源与来自不同来源的资源之间的交互。您可以使用本地服务器:设置一个本地服务器(例如,使用Node.js或Python的SimpleHTTPServer)并从那里提供您的文件。通过本地服务器的URL(例如,“http://localhost:8000”)访问文件,可以避免CORS错误。
推荐:https://github.com/JacksonTian/anywhere

相关问题