Nodejs Index.html加载链接和脚本404

我有一个nodejs服务器运行客户端封装在一个客户端文件夹,使pipe理index.html文件夹结构容易。 然后链接和脚本应该加载没有问题。

client folder /index.html /style.css /script.js closer folder /closure /etc. app.js package.json utility.js 

在我的app.js文件中,我有一个正常的

 app.get ('/', function (req,res) { res.render('index.html'); }); 

当我运行并去到本地主机端口的文件加载,但是当我打开铬控制台,我看到index.html文件未能加载任何脚本404错误未find。 我注意到,在很多快速应用程序中,似乎有一些沿着这个方向的常见模式

 this app.set('views', __dirname + '/client'); this app.use(express.static(__dirname + "./client")); this app.use('client', express.directory('client')); 

但我没有看到app.use和app.set之间的区别的解释,也没有一个很好的解释,我能find的最好的

app.set('views',__dirname +'/ views'):使用./views作为客户端模板的默认path

来自Alex Young的文章,但即使这样对我来说也是有点稀疏和干燥的,我希望对这个索引文件为什么可能无法在同一目录级别加载链接的原因做一个更深入的解释。

 <link rel="stylesheet" type="text/css" href="style.css" /> 

我看着这个,我找不到问题。

从答案Express-js不能得到我的静态文件,为什么? 我会build议:

 app.use("/client", express.static(__dirname + '/client')); 

这是需要的,因为你的:

 app.get ('/', function (req,res) { res.render('index.html'); }); 

只是解决了当有人去/或说应该服务index.html时发生的事情。 这本身并没有其他的东西。

只需从项目的根目录运行你的服务器即可。 这将解决这个问题,因为你使用了相对寻址。