Warm tip: This article is reproduced from serverfault.com, please click

javascript-Node.js找不到客户端文件

(javascript - Node.js cannot find client-side files)

发布于 2020-11-30 03:15:49

我有一个简单的node.js应用程序:

server.js

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

const PORT = 8080;

app.use(express.static('client'));

// Start the express web server listening on 8080
app.listen(8080, () => {
  console.log('Service started on port 8080.');
});

// Serve the homepage
app.get('/', (req, res) => {
  res.sendFile(__dirname + '/index.html');
});

index.html

<html>
... irrelevant junk ...
<script src="js/client.js"></script>
</html>

但是,当我运行node server.js并打开时localhost:8080,控制台会抱怨找不到它http://localhost:8080/javascript/client.js

显然,我希望它正在查看./javascript/client.js,而不是植根于locahost addr -如何解决?

文件夹层次结构很简单:

.
├── index.html
├── server.js
├── js
    └── client.js

我想改变publicclient的建议在这里,但没有帮助。

Questioner
Alex Coleman
Viewed
0
jfriend00 2020-11-30 11:35:19

根据文件在服务器上的位置,你应该进行三处更改:

app.use(express.static("./public"));

并且,在客户端中,使用以下命令:

<script src="/js/client.js"></script>

然后,将服务器端文件下方的客户端文件移动到根公共目录中,如下所示:

.
├── index.html
├── server.js
├── public
    ├── js
        └── client.js

无需将客户端文件移入public,则可以打开服务器端代码以供客户端读取(不需要)。


运作方式如下:

客户要求:

http://localhost:8080/js/client.js

express.static() 看到以下要求:

 /js/client.js

它从你的公共文件的根目录开始,并合并/js/client.js到公共目录路径,然后创建正确的访问路径:

public/js/client.js

通过执行以下操作,你可以使它工作而无需将客户端文件移到public目录层次结构中:

app.use(express.static(__dirname));

但是,那样就可以打开所有服务器端文件,以供你真正不希望的客户端读取。