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

JavaScript通过src引入文件在Live Server正常但localhost报错的原因咨询

问题原因分析

这个错误的核心是两个服务器的根目录不一致,导致相对路径解析结果不同:

  • 用Live Server打开时,URL是http://127.0.0.1:5500/test/test.html,此时服务器的根目录是test文件夹的上级目录。页面里的./js/common.js会被解析为http://127.0.0.1:5500/test/js/common.js,刚好匹配实际文件路径,所以能正常加载common.js,test函数可用。
  • 用http://localhost:8081/test.html打开时,服务器的根目录是test.html所在的目录。页面里的./js/common.js会被解析为http://localhost:8081/js/common.js,但实际js文件夹是在test目录下,服务器找不到这个文件,导致common.js加载失败,自然就找不到test函数,抛出Uncaught ReferenceError。

你可以打开浏览器开发者工具的「网络」面板,查看第二个服务器下common.js的请求状态,大概率是404错误,验证这个结论。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.10 22:01:10