【发布时间】:2018-02-02 13:54:24
【问题描述】:
谁能帮我理解我的代码做错了什么。当服务器将 index.html 文件发送到浏览器时,为什么我的 javascript 或 css 文件无法运行?
我有一个非常基本的 html 页面、javascript 页面和 express 服务器。我对某事感到困惑。如果我通过启动应用程序然后在我的 url 栏中键入:localhost:3000 来访问 html,则浏览器将按预期提供 index.html。但是,我的 javascript 中的所有脚本都不起作用(没有 console.logs 运行,并且未附加事件处理程序)。另一方面,如果我将绝对文件路径粘贴到 url 栏中(无论服务器是否运行),scripts.js 文件 确实 工作。
这是我的基本文件:
index.html
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>music</title>
<link rel="stylesheet" type="text/css" href="style.css">
<script src="scripts.js"></script>
</head>
<body>
<p>I am the html</p>
<button id="myButton">click here</button>
</body>
</html>
scripts.js:
window.onload = function(e) { console.log('js 文件已加载');
让按钮 = document.getElementById('myButton');
button.addEventListener('click', function(e) { console.log('按钮被点击'); }); };
app.js
const express = require('express'); const app = express();
app.get('/', function (req, res) {
res.sendFile('/Users/myName/webPage/index.html'); });app.listen(3000);
启动服务器:nodemon app.js
谢谢!
【问题讨论】:
-
澄清情况:
标签: javascript node.js express