【问题标题】:JavaScript and CSS files not linking in App (using Express) [duplicate]JavaScript 和 CSS 文件未在 App 中链接(使用 Express)[重复]
【发布时间】: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


【解决方案1】:

由于您配置快速服务器的方式,您正面临此问题。目前,根据配置,无论您为 index.html 文件提供什么获取请求。您的 JS、CSS、图像等是静态文件,您需要稍微不同地处理它。

看看这个链接https://expressjs.com/en/starter/static-files.html。修改你的 server.js 文件

const express = require('express'); const app = express();

app.use(express.static(__dirname + '/public')); //Add this line. Change public to whatever location your static assets are stored at

app.get('/', function (req, res) {
res.sendFile('/Users/myName/webPage/index.html'); 
});

app.listen(3000);

【讨论】:

    猜你喜欢
    • 2020-06-04
    • 2022-08-16
    • 2012-11-15
    • 2012-10-31
    • 2020-10-09
    • 2023-01-16
    • 2023-01-26
    • 2012-10-23
    • 1970-01-01
    相关资源
    最近更新 更多