【问题标题】:NodeJS server failed to load JavaScript modulesNodeJS 服务器无法加载 JavaScript 模块
【发布时间】:2021-10-04 09:48:55
【问题描述】:

SO 公民。我将 Node.js 与 Express.js 一起用于 Web 应用程序的服务器端。当网络服务器尝试绑定源代码中的引用时,我经常遇到问题。 我的应用程序的结构是:

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() 函数将html 文件以绝对路径传递给index.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.jsplanListItem.js。我应该怎么做才能让 Node 找到这些文件???

【问题讨论】:

    标签: javascript node.js express import routes


    【解决方案1】:

    您也需要为utils 服务。你可以添加

    app.use('/utils', express.static("src/utils"))
    

    之后

    app.use(express.static("src/static"))
    

    HTML 文档中的所有路径都在浏览器上进行评估。浏览器为每次导入发送一个请求。您的服务器必须处理这些请求。

    【讨论】:

      猜你喜欢
      • 2017-02-22
      • 2017-02-05
      • 2020-05-23
      • 2012-07-09
      • 1970-01-01
      • 2017-06-26
      • 1970-01-01
      • 2020-10-01
      • 2022-11-15
      相关资源
      最近更新 更多