Express项目运行app.js无法读取public/js下index.js报错
问题描述
我将index.js文件存放在外部文件夹中,且在该文件内使用了jQuery,但尝试运行app.js时出现报错,以下为相关代码、目录结构及报错详情:
app.js 代码
const express = require('express'); const https = require('https'); const bodyParser = require('body-parser'); const jquery = require('jquery'); const app=express(); app.use('/jquery', express.static(__dirname + '/node_modules/jquery/dist/')); const inputs=require(__dirname+'\\public\\js\\index') app.use(bodyParser.urlencoded({extended: true})); app.use(express.static("public")); app.get("/",function(req, res){ res.sendFile(__dirname+"/index.html"); }); app.listen(5000, function(){ console.log("The server is started on port 5000"); });
项目目录结构

运行报错信息

报错原因
核心问题是混淆了Node.js后端运行环境和浏览器前端运行环境的代码边界:
- jQuery是面向浏览器环境的DOM操作库,常规Express项目不需要在后端服务代码中通过
require()引入 public/js/index.js是运行在用户浏览器中的前端脚本,依赖浏览器提供的window、document等全局DOM对象,直接在后端Node环境用require()加载该文件时,Node找不到浏览器专属的API,就会抛出截图中显示的引用错误。
修复方案
- 删除
app.js中两行错误的后端引入代码:- 移除
const jquery = require('jquery'); - 移除
const inputs=require(__dirname+'\\public\\js\\index')
- 移除
- 在前端入口文件
index.html的</body>闭合标签前,按顺序引入jQuery和自定义的index.js脚本即可,你之前配置的jQuery静态资源托管规则可以保留不用修改:
<!-- 引入托管的jQuery库 --> <script src="/jquery/jquery.min.js"></script> <!-- 引入public目录下的自定义前端脚本 --> <script src="/js/index.js"></script>
- 优化路径拼接逻辑,避免Windows反斜杠导致的跨系统兼容问题,推荐使用Node内置
path模块处理路径,修改后的完整app.js代码如下:
const express = require('express'); const https = require('https'); const bodyParser = require('body-parser'); const path = require('path'); const app = express(); // 托管jQuery静态资源 app.use('/jquery', express.static(path.join(__dirname, 'node_modules/jquery/dist/'))); // 解析表单请求体 app.use(bodyParser.urlencoded({extended: true})); // 托管public目录下所有前端静态资源 app.use(express.static(path.join(__dirname, "public"))); app.get("/",function(req, res){ res.sendFile(path.join(__dirname, "index.html")); }); app.listen(5000, function(){ console.log("The server is started on port 5000"); });
修改完成后重启Node服务,访问http://localhost:5000即可正常加载页面,jQuery和自定义前端脚本会在浏览器环境正常执行,不会再出现之前的报错。
内容的提问来源于stack exchange,提问作者Satyam Adarsh
相关产品推荐
相关产品推荐

