【发布时间】: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文件<script type="text/javascript" src="./src/index.js"></script>确保文件的路径正确。 -
有关安全检查的消息只是 404 错误的结果。 javascript 文件在 url localhost:4800/server/app.js 中不存在 - 您应该确保它确实存在并且名称拼写正确(也是小写/大写)
标签: javascript html node.js google-chrome