NodeJS 服务器无法加载 JavaScript 个模块
NodeJS server failed to load JavaScript modules
所以公民。我在 Web 应用程序的服务器端使用 Node.js 和 Express.js。当网络服务器试图绑定来自源代码的引用时,我经常遇到问题。
我的应用程序的结构是:
src/
- static/
- calendar.js
- client.js
- planner.js
- index.html
- utils/
- planListItem.js
- selectedDates.js
- index.js
- server.js
在index.js
import app from "./server.js"
在server.js
我用回调函数注册了一个端点“/”,该函数通过 res.sendFile()
函数将绝对路径传递回 index.html
.
发回 html
文件
里面index.html
<html>
<head>...</head>
<body>
...
<script type="module" src="./client.js"></script>
</body>
</html>
到目前为止服务器已成功加载脚本。但是后来
client.js
import { initCalendar } from "./calendar.js"
calendar.js
import Planner from "./planner.js";
import selectedDays from "../utils/selectedDates"
planner.js
import {PlanListItem} from "./../utils/planListItem.js";
足够的结构:)
我想问题在于 Express 如何路由静态文件,因为源代码参考已经过 1000 次检查并且是正确的。
为了保护自己不受污秽建议的影响,我预先在 server.js 中添加了以下脚本 app.use(express.static("src/static"))
。这应该有助于提供脚本。但不幸的是浏览器响应
很明显Node在utils/下找不到selectedDates.js
和planListItem.js
。我应该怎么做才能让 Node 找到这些文件???
你也需要服务 utils
。您可以添加
app.use('/utils', express.static("src/utils"))
之后
app.use(express.static("src/static"))
HTML 文档中的所有路径都在浏览器上进行评估。浏览器为每次导入发送一个请求。您的服务器必须处理这些请求。
所以公民。我在 Web 应用程序的服务器端使用 Node.js 和 Express.js。当网络服务器试图绑定来自源代码的引用时,我经常遇到问题。 我的应用程序的结构是:
src/
- static/
- calendar.js
- client.js
- planner.js
- index.html
- utils/
- planListItem.js
- selectedDates.js
- index.js
- server.js
在index.js
import app from "./server.js"
在server.js
我用回调函数注册了一个端点“/”,该函数通过 res.sendFile()
函数将绝对路径传递回 index.html
.
html
文件
里面index.html
<html>
<head>...</head>
<body>
...
<script type="module" src="./client.js"></script>
</body>
</html>
到目前为止服务器已成功加载脚本。但是后来
client.js
import { initCalendar } from "./calendar.js"
calendar.js
import Planner from "./planner.js";
import selectedDays from "../utils/selectedDates"
planner.js
import {PlanListItem} from "./../utils/planListItem.js";
足够的结构:)
我想问题在于 Express 如何路由静态文件,因为源代码参考已经过 1000 次检查并且是正确的。
为了保护自己不受污秽建议的影响,我预先在 server.js 中添加了以下脚本 app.use(express.static("src/static"))
。这应该有助于提供脚本。但不幸的是浏览器响应
很明显Node在utils/下找不到selectedDates.js
和planListItem.js
。我应该怎么做才能让 Node 找到这些文件???
你也需要服务 utils
。您可以添加
app.use('/utils', express.static("src/utils"))
之后
app.use(express.static("src/static"))
HTML 文档中的所有路径都在浏览器上进行评估。浏览器为每次导入发送一个请求。您的服务器必须处理这些请求。