404在nodejs+Ionic应用程序中从index.html中的另一个文件夹导入js文件时出错

404 error while import js file from another folders in index.html in nodejs + Ionic app

本文关键字:js 文件夹 导入 文件 出错 另一个 html nodejs+Ionic 应用程序 index      更新时间:2023-09-26

我有一个错误,正试图解决它好几个小时。我的文件结构:

-/node_modules
-/www
---bundle.js
---index.html

在index.html中我有这样的代码

<script src="node_modules/ng-cordova/dist/ng-cordova.min.js" type="text/javascript"></script>
<!-- cordova script (this will be a 404 during development) -->
<script src="cordova.js"></script>
<script src="bundle.js"></script>

问题是bundle.js包含得很好,但ng-cordova.min.js给出404错误

Cannot GET /node_modules/ng-cordova/dist/ng-cordova.min.js

编辑:我也尝试过,但没有成功

<script src="/node_modules/ng-cordova/dist/ng-cordova.min.js" type="text/javascript"></script>
<script src="../node_modules/ng-cordova/dist/ng-cordova.min.js" type="text/javascript"></script>

我不使用expressexpress.static

根据您的项目结构判断,我打赌它是由Express.js提供的。我还打赌www文件夹在Express应用程序中被设置为静态文件夹,如下所示:

app.use('/', express.static(path.join(__dirname, www)));

在这种情况下,您的服务器将只提供位于www文件夹中的文件。您需要在www文件夹中包括任何客户端依赖项:

-/node_modules/
-/www/
--lib/
---ng-cordova/
--bundle.js
--index.html

然后像这样加载它们:

<script src="lib/ng-cordova/dist/ng-cordova.min.js" type="text/javascript"></script>

更新

只需将node_modules放在www文件夹中,它就可以正常工作。

这里的问题是,您试图从index.html文件夹加载ng cordova.min.js文件。您应该更改:

<script src="node_modules/ng-cordova/dist/ng-cordova.min.js" type="text/javascript"></script>

为此:

<script src="../node_modules/ng-cordova/dist/ng-cordova.min.js" type="text/javascript"></script>

您试图从错误的目录加载文件。您必须使用以下路径:

src="../node_modules/

或者这个:

src="/node_modules"

如果上面的目录是您的根目录。

同样令人困惑的是,你评论错误的那一行并不是错误的实际来源。你为什么两次试图链接到该文件?

//编辑:由于罗曼比我快一分钟,他应该得到正确答案的奖励,我想说:p只有当它真的解决了你的问题时