【发布时间】:2018-08-27 17:19:41
【问题描述】:
我在将 JavaScript 文件链接到 HTML 文件时遇到了一个大问题。
我的 HTML 代码:
<!DOCTYPE html>
<html>
<head>
<title>Express App</title>
</head>
<body>
<h1>GET Requests</h1><br/>
<input type="number" name="id" id="id-input>
<button type="submit" onclick="findPerson()">Submit</button>
<script src="./index.js" type="text/javascript"></script>
</body>
</html>
这段代码看起来还不错,其实这是我的JavaScript代码:
const express = require('express');
const app = express();
const server = 'http://localhost:3000';
app.connect(server);
app.get('/', (req, res) => {
res.sendFile(__dirname + "/" + "index.html");
});
const findPerson = () => {
var ID = window.document.getElementById('id-
input').value;
console.log(ID);
};
app.listen(8080, () => {
console.log('App is listening on port 8080');
});
现在,由于某种原因,当我检查页面并转到控制台时,它会说:
Refused to execute script from
'http://localhost:8080/index.js' because
its MIME type ('text/html') is not executable, and
strict MIME type checking is enabled.
还有这个:
Failed to load resource: the server responded with
a status of 404 (Not Found) index.js:1
【问题讨论】:
-
您不应尝试将
Node.js文件加载到浏览器中。将后端与前端问题分开。 -
您尝试运行的脚本需要在带有 Node.js 的网络服务器上运行。然后,您可以通过例如与此网络服务器进行通信。 Ajax 请求。这可以通过像
axios这样的库来完成。您在这里混淆了担忧。 -
您的
index.js需要在服务器端运行。例如node index.js。如果您正在开始 Node.js 开发,那么您可以从入门工具包开始阅读他们的readme.md。谢谢。 -
请阅读Under what circumstances may I add “urgent” or other similar phrases to my question, in order to obtain faster answers? - 总结是这不是解决志愿者的理想方式,并且可能会适得其反。请不要将此添加到您的问题中。
标签: javascript jquery html express