运行项目时遭遇Uncaught TypeError:无法读取undefined的prototype
解决Express在前端Webpack环境中抛出的
Cannot read properties of undefined (reading 'prototype')错误 问题场景
控制台持续抛出类型错误,指向express库的response.js第41行,尝试读取http.ServerResponse.prototype但http对象未定义,错误栈显示该依赖从前端组件NewProduct.js引入。
错误日志
Uncaught TypeError: Cannot read properties of undefined (reading 'prototype') at Object.<anonymous> (response.js:41:1) at ./node_modules/express/lib/response.js (response.js:1105:1) at __webpack_require__ (bootstrap:782:1) at fn (bootstrap:150:1) at ./node_modules/express/lib/express.js (express.js:21:1) at __webpack_require__ (bootstrap:782:1) at fn (bootstrap:150:1) at ./node_modules/express/index.js (index.js:11:1) at __webpack_require__ (bootstrap:782:1) at fn (bootstrap:150:1) at ./src/components/admin/NewProduct.js (NewProduct.css?268e:45:1) at __webpack_require__ (bootstrap:782:1) at fn (bootstrap:150:1) at ./src/App.js (App.css?da7c:45:1) at __webpack_require__ (bootstrap:782:1) at fn (bootstrap:150:1) at ./src/index.js (index.css?02e3:45:1) at __webpack_require__ (bootstrap:782:1) at fn (bootstrap:150:1) at 0 (store.js:46:1) at __webpack_require__ (bootstrap:782:1) at checkDeferredModules (bootstrap:45:1) at Array.webpackJsonpCallback [as push] (bootstrap:32:1) at main.chunk.js:1:57
报错代码片段
/** * Response prototype. * @public */ var res = Object.create(http.ServerResponse.prototype); /** * Module exports. * @public */ module.exports = res;
原因分析
Express是Node.js后端框架,依赖Node.js核心模块(如http),而浏览器环境中没有这些模块。在前端代码中直接引入Express,Webpack打包时无法解析http模块,导致抛出该错误。
解决方案
- 移除前端代码中的Express引用:检查
NewProduct.js及其他前端文件,删除所有import express from 'express'或const express = require('express')这类代码,Express不应该出现在前端代码里。 - 改用HTTP客户端调用后端接口:如果需要和后端服务交互,使用
fetch、axios等前端HTTP工具发送请求,不要直接在前端引入后端框架。 - 清理不必要的依赖(可选):如果前端项目误装了Express,执行
npm uninstall express(或对应yarn/pnpm命令)移除该包,再重新打包项目。
内容的提问来源于stack exchange,提问作者Mustafa Abdeali
相关产品推荐
相关产品推荐

