Nodejs Index.html加载但链接&脚本404 [英] Nodejs Index.html Loads but Links & Scripts 404

查看:306
本文介绍了Nodejs Index.html加载但链接&脚本404的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我将一个nodejs服务器与客户端一起封装在客户端文件夹中运行,以便管理index.html的文件夹结构。

I have a nodejs server running with the client side encapsulated in a client folder to make managing the folder structure for index.html easy. Then the links and scripts should load no problem.

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

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

In my app.js file I have a normal

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

当我运行并转到本地主机端口时,文件加载,但是当我打开chrome控制台,我看到index.html文件无法加载任何404错误未找到的脚本。我注意到,在很多快递应用程序中,似乎有一些沿着

and when I run and go to the local host port the file loads, but when I open the chrome console, I see that the index.html file failed to load any of the scripts with a 404 error not found. I notice that in a lot of express apps there seems to be a common pattern of something along the lines of

this app.set('views', __dirname + '/client');

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

this app.use('client', express.directory('client'));

但是我没有看到app.use和app.set之间的差异的解释,也没有一个很好的解释,我能找到的最好的是

but I don't see an explanation on the difference between app.use and app.set, nor a good explanation, the best the I could find was


app.set('views',__dirname +'/ views'):Use ./views作为客户端模板的默认
路径

app.set('views', __dirname + '/views'): Use ./views as the default path for the client-side templates

from Alex Young的文章,但即使这对我来说有点稀疏和干燥,我希望有一个对于为什么索引文件可能无法加载与它相同的目录级别的链接的解释有点深入。

from Alex Young's article but even this was a little sparse and dry for me, I'm hoping for a bit deeper of an explanation as to why the index file might be unable to load a link on the same directory level as it.

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

我看了看,发现问题不存在。

I look at this and I can't find the problem.

推荐答案

从答案 Express-js无法获取我的静态文件,为什么?我会建议:

From the answer Express-js can't GET my static files, why? I'd suggest:

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

这是因为您的:

This is needed because your:

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

只能解决当有人前往 / 并说应该提供index.html。这本身并不适用于其他任何事情。

is only addressing what happens when someone goes to / and saying that index.html should be served. That alone doesn't serve anything else.

这篇关于Nodejs Index.html加载但链接&amp;脚本404的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆