Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/javascript/473.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/node.js/36.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
应用程序中未链接的JavaScript和CSS文件(使用Express)_Javascript_Node.js_Express - Fatal编程技术网

应用程序中未链接的JavaScript和CSS文件(使用Express)

应用程序中未链接的JavaScript和CSS文件(使用Express),javascript,node.js,express,Javascript,Node.js,Express,有人能帮我理解我的代码哪里做错了吗。当服务器将index.html文件发送到浏览器时,为什么我的javascript或css文件不运行 我有一个非常基本的html页面、javascript页面和express服务器。我有些困惑。如果我通过启动应用程序,然后在我的url栏中键入:localhost:3000来访问html,那么浏览器将按照预期使用index.html。但是,我的javascript中没有任何脚本可以工作(没有运行任何console.log,也没有附加事件处理程序)。另一方面,如果我

有人能帮我理解我的代码哪里做错了吗。当服务器将index.html文件发送到浏览器时,为什么我的javascript或css文件不运行

我有一个非常基本的html页面、javascript页面和express服务器。我有些困惑。如果我通过启动应用程序,然后在我的url栏中键入:localhost:3000来访问html,那么浏览器将按照预期使用index.html。但是,我的javascript中没有任何脚本可以工作(没有运行任何console.log,也没有附加事件处理程序)。另一方面,如果我将绝对文件路径粘贴到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>

音乐
我是html

点击这里
scripts.js:

window.onload=函数(e){console.log('js文件已加载');
let button=document.getElementById('myButton');
按钮。addEventListener('click',函数(e){ log('按钮被点击';});}

app.js

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

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

app.listen(3000)

使用:nodemon app.js启动服务器


谢谢大家!

由于您配置express server的方式,您正面临此问题。目前,根据配置,无论是任何get请求,您都会为index.html文件提供服务。您的JS、CSS、图像等都是静态文件,您需要以稍微不同的方式处理它

看看这个链接。修改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);

你可以看看这里:为了澄清情况: