You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Express.js静态JS文件无法加载至客户端浏览器问题求助

问题根源与解决方案

你的问题出在静态资源的引用路径错误,具体是浏览器端路径写法不符合Web标准,且未正确使用Express静态资源挂载的绝对路径前缀。

问题分析

  1. 路径分隔符错误:你在EJS中使用了Windows系统的反斜杠\,但浏览器URL必须使用正斜杠/。部分资源(比如图片)可能因浏览器自动兼容加载成功,但JS文件会因路径解析失败无法加载。
  2. 相对路径的不确定性:当前页面URL为/new-post,使用../public这类相对路径容易出现解析偏差。而Express已将public文件夹挂载为/public开头的绝对路径资源,应直接用该前缀引用静态资源。

修复步骤

修改views/new_post.ejs中的资源引用路径,全部改为基于/public的绝对路径,同时替换反斜杠为正斜杠:

<!DOCTYPE html>
<html>
  <head>
    <script src="https://cdn.ckeditor.com/ckeditor5/35.4.0/classic/ckeditor.js"></script>
  </head>
  <body>
    <img src="/public/dog-img.jpg" alt="derp" />
    <h1>Classic editor</h1>
    <div id="editor">
      <p>This is some sample content.</p>
    </div>
    <script
      src="/public/js_scripts/new_post.js"
      type="application/javascript"
    ></script>
  </body>
</html>

验证逻辑

Express通过app.use("/public", express.static(path.join(__dirname, "public")))将本地public文件夹映射到http://localhost:5000/public路径下,所有静态资源都应以/public开头访问。修改后,浏览器会正确请求http://localhost:5000/public/js_scripts/new_post.js,该路径能被Express静态资源中间件正确解析并返回对应JS文件,CKEditor即可正常初始化。

内容的提问来源于stack exchange,提问作者Alex B

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.03 11:10:21