我应该在哪里放置自定义 javascript 模块,以便浏览器可以找到它
Where should I put a custom javascript module so that it can be found by the browser
我的项目文件结构如下:
config.js
是我想在客户端和服务器之间共享的模块。
在服务器端文件app.js
中,我写了var config = require('./config');
,可以正确找到并包含该模块。我还写了 app.use(express.static(path.resolve(__dirname, 'client')));
以便将文件夹 client
中的文件提供给客户端。
然而,在客户端html文件index.html
中,我写了
<script src="/config/config.js"></script>
<script src="config.js"></script>
但它们都导致 404 Not found 错误。我应该把 config.js
放在哪里,如何将它包含在客户端?
解释:
您的 config.js
实际上是您的客户无法联系到的。通过
app.use(express.static(path.resolve(__dirname, 'client')));
您告诉您的应用在 client
文件夹中查找请求的 url 并提供匹配 url.
的文件
(例如,访问 http://127.0.0.1/ref.html
将导致您的应用程序在 client
文件夹中查找名为 ref.html
的文件。如果找到,它将被简单地发送回。否则,您将面临 404
.)
知道了这一点,我们可以得出结论
<script src="/config/config.js"></script>
找不到任何东西。它会在 client
中寻找文件夹 config
,但不会看到它。第一个404
.
同路,
<script src="config.js"></script>
将要求在您的 client
文件夹中 找到一个名为 config.js
的文件。另一个 404
.
分辨率:
您只需将其放入 client
文件夹并将您的 var config = require('./config');
更改为 var config = require('./client/config');
。
然后您就可以在 html 中使用 <script src="/config.js"></script>
。 (请注意我添加到路径中的 /
。那是因为您希望它位于您网站的根目录中。)
我的项目文件结构如下:
config.js
是我想在客户端和服务器之间共享的模块。
在服务器端文件app.js
中,我写了var config = require('./config');
,可以正确找到并包含该模块。我还写了 app.use(express.static(path.resolve(__dirname, 'client')));
以便将文件夹 client
中的文件提供给客户端。
然而,在客户端html文件index.html
中,我写了
<script src="/config/config.js"></script>
<script src="config.js"></script>
但它们都导致 404 Not found 错误。我应该把 config.js
放在哪里,如何将它包含在客户端?
解释:
您的 config.js
实际上是您的客户无法联系到的。通过
app.use(express.static(path.resolve(__dirname, 'client')));
您告诉您的应用在 client
文件夹中查找请求的 url 并提供匹配 url.
的文件
(例如,访问 http://127.0.0.1/ref.html
将导致您的应用程序在 client
文件夹中查找名为 ref.html
的文件。如果找到,它将被简单地发送回。否则,您将面临 404
.)
知道了这一点,我们可以得出结论
<script src="/config/config.js"></script>
找不到任何东西。它会在 client
中寻找文件夹 config
,但不会看到它。第一个404
.
同路,
<script src="config.js"></script>
将要求在您的 client
文件夹中 找到一个名为 config.js
的文件。另一个 404
.
分辨率:
您只需将其放入 client
文件夹并将您的 var config = require('./config');
更改为 var config = require('./client/config');
。
然后您就可以在 html 中使用 <script src="/config.js"></script>
。 (请注意我添加到路径中的 /
。那是因为您希望它位于您网站的根目录中。)