【问题标题】:Not able to move javascript from index.html into external file无法将 javascript 从 index.html 移动到外部文件
【发布时间】:2018-09-09 08:53:04
【问题描述】:

我正在开发一个简单的 tensorflow.js 项目,如果我将 js 代码直接放在 index.html 文件中,我可以毫无错误地运行所有内容,但如果我尝试引用外部 js 文件,则会出现错误(这是在 Chrome 中——尽管我在 Firefox 中也遇到了错误):

<!DOCTYPE html>
<html lang="en">

<head>
  <meta charset="utf-8">
  <title>Playing with TensorFlow.js</title>
  <!-- Load TensorFlow.js -->
  <script src="https://cdn.jsdelivr.net/npm/@tensorflow/tfjs@0.12.5"> </script>
  <!-- Place your code in the script tag below. You can also use an external .js file -->
  <script type = "text/javascript" src = "../server/app.js"></script>
</head>

<body>
</body>

</html>

并且被引用的外部 JS 文件包含以下代码:

// Define a model for linear regression.
const model = tf.sequential();
model.add(tf.layers.dense({ units: 1, inputShape: [1] }));

// Prepare the model for training: Specify the loss and the optimizer.
model.compile({ loss: 'meanSquaredError', optimizer: 'sgd' });

// Generate some synthetic data for training.
const xs = tf.tensor2d([1, 2, 3, 4], [4, 1]);
const ys = tf.tensor2d([1, 3, 5, 7], [4, 1]);

// Train the model using the data.
model.fit(xs, ys, { epochs: 10 }).then(() => {
  // Use the model to do inference on a data point the model hasn't seen before:
  // Open the browser devtools to see the output
  model.predict(tf.tensor2d([5], [1, 1])).print();
});

上面的代码看起来正确吗?这只是 Chrome 安全默认设置吗?有没有办法解决这个问题?

顺便说一句,这是错误:

GET http://localhost:4800/server/app.js 404 (未找到) localhost/:1

拒绝执行来自“http://localhost:4800/server/app.js”的脚本 因为它的 MIME 类型 ('text/html') 是不可执行的,并且严格的 MIME 类型检查已启用。

【问题讨论】:

  • 您的错误控制台中是否有任何显示?否则,请尝试在整个文件中随机添加 console.log 语句,看看您是否可以查看它们。
  • 错误是什么?
  • 添加了上面的错误。
  • 它似乎对我有用:codesandbox.io/s/j1zpjpyr79。能够让它与您类似的文件夹结构一起工作。唯一不同的是我如何访问js 文件&lt;script type="text/javascript" src="./src/index.js"&gt;&lt;/script&gt; 确保文件的路径正确。
  • 有关安全检查的消息只是 404 错误的结果。 javascript 文件在 url localhost:4800/server/app.js 中不存在 - 您应该确保它确实存在并且名称拼写正确(也是小写/大写)

标签: javascript html node.js google-chrome


【解决方案1】:

这听起来很傻,但是文件名中有拼写错误吗?浏览器找不到文件。该文件肯定在“服务器”文件夹中吗?也许,尝试将 .js 文件放在根文件夹中,并且只使用 Javascript 文件名而没有任何目的地。从表面上看,这将是一个简单但愚蠢的错误。

【讨论】:

  • 我使用 VSC 来帮助我找到文件,使用 intellsense,我已经三重检查了它,它是正确的。
  • 另外,如果只是找不到文件,我不清楚错误消息是什么(见上文)。当然,如果是这种情况,那将是错误消息。
  • 啊,我找到了解决办法。所以我认为问题在于,因为我使用的是 express,它只在“静态”文件夹中查找与 index.html 相关的文件。所以我把 app.js 文件移到了那里,对 index.html 中的位置进行了适当的更新,瞧,它起作用了。 :)
  • 错误信息为404,表示找不到文件。确保服务器文件夹位于项目的根目录中,因为知道 Visual Studio,您的索引文件实际上位于 View 文件夹中,而不是位于项目的根目录中
猜你喜欢
  • 1970-01-01
  • 2015-05-21
  • 2023-02-04
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2014-01-28
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多