簡體   English   中英

嘗試使用導入的 js 函數啟動 html 頁面時,“CORS 策略已阻止從源‘null’訪問腳本”錯誤

[英]"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

我在嘗試使用從另一個文件導入函數的 javascript 文件啟動 html 頁面時遇到此錯誤:

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

這是html代碼:

<!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>

從 html 調用的 js 文件:(funcexecute.js)

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

導入的模塊:(funcfile.js)

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

我怎樣才能解決這個問題? (我正在使用 vscode)

如果不使用服務器,就不能將腳本文件用作模塊。 看看這里

以下是一些選項

  • 使用 Live Server(VS Code 的擴展)
  • 使用 node 中的http-server模塊(通過 npm 安裝,然后從項目目錄運行http-server .
  • 使用 python 中的http.server
  • 使用 wamp(或燈)服務器

總之不能使用type="module"文件協議

右鍵單擊 Visual Studio Code 中的index.html文件,選擇Open with Live Server
這將解決您的問題。

JS 中的導出/導入僅適用於服務器,它們不適用於本地機器(有不同的代碼)。
這是如何做到這一點,分步說明

  1. type = "module"通常與 webpack 一起使用。

  2. 如果不使用webpack,則需要啟動一個靜態服務

  3. 你可以使用http-server -p 8003啟動服務

問題是因為文件是直接打開的; 所以似乎有幾種方法可以解決這個問題:一種是禁用 Chrome 中的安全性,盡管盡我所能,但我無法讓它放棄幽靈:我嘗試了圍繞 –disable- 的各種組合Chrome 的網絡安全標志。

第二種選擇是在本地托管站點。 有那么一瞬間,我考慮使用 IIS Express 之類的東西; 但幸運的是,我遇到了這個工具,它可以為您在本地托管一個站點。

它可以作為 npm 包安裝: npm install --global http-server 安裝后,您只需導航到相關目錄,然后鍵入 http-server:

 C:\\repos\\webanimations\\animated-columns-optimised>http-server Starting up http-server, serving ./ Available on: http://192.168.1.79:8080 http://127.0.0.1:8080 http://172.17.230.225:8080 Hit CTRL-C to stop the server

然后您可以導航到您的特定頁面; 例如:

 http://127.0.0.1:8080/columns

並且沒有更多的 CORS 錯誤(還不太有效,但那是一個完全不同的故事)。

將腳本鏈接中的type="module"替換為type="JavaScript"

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM