如何解决Node.js环境中npm start时的'ReferenceError: Request is not defined'错误?
解决Node.js运行
npm start时ReferenceError: Request is not defined错误 问题场景
运行npm start启动项目时,持续抛出ReferenceError: Request is not defined错误,错误指向node_modules/@expo/server/src/environment.ts文件,该文件代码片段如下:
"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.installGlobals = exports.ExpoResponse = exports.ExpoRequest = void 0; /* eslint-disable no-var */ const node_1 = require("@remix-run/node"); /** @deprecated */ exports.ExpoRequest = Request; /** @deprecated */ exports.ExpoResponse = Request; function installGlobals() { (0, node_1.installGlobals)(); global.ExpoRequest = Request; global.ExpoResponse = Response; } exports.installGlobals = installGlobals;
错误栈信息:
ReferenceError: Request is not defined at Object. (/Users/Theo/nunj/node_modules/@expo/server/src/environment.ts:23:28) at Module._compile (node:internal/modules/cjs/loader:1105:14) at Object.Module._extensions..js (node:internal/modules/cjs/loader:1159:10) at Module.load (node:internal/modules/cjs/loader:981:32) at Function.Module._load (node:internal/modules/cjs/loader:822:12) at Module.require (node:internal/modules/cjs/loader:1005:19) at require (node:internal/modules/cjs/helpers:102:18) at Object. (/Users/Theo/nunj/node_modules/@expo/server/install.js:1:28) at Module._compile (node:internal/modules/cjs/loader:1105:14) at Object.Module._extensions..js (node:internal/modules/cjs/loader:1159:10)
错误原因分析
- 全局对象版本限制:
Request和Response是Node.js 18.x及以上版本才默认提供的全局对象,若Node.js版本低于18.x,会直接触发该错误。 - 包代码逻辑缺陷:
- 模块加载阶段直接引用未定义的
Request,此时用于注入全局对象的installGlobals()还未执行。 - 代码存在笔误:
exports.ExpoResponse = Request应为exports.ExpoResponse = Response。
- 模块加载阶段直接引用未定义的
解决方案
1. 升级Node.js版本
若当前Node.js版本低于18.x,直接升级到18.x或更高LTS版本,升级后Request/Response会成为全局对象,可直接解决问题。
2. 临时修复包代码(应急用)
修改node_modules/@expo/server/src/environment.ts文件,从@remix-run/node显式导入Request和Response,并修正笔误:
"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.installGlobals = exports.ExpoResponse = exports.ExpoRequest = void 0; /* eslint-disable no-var */ const node_1 = require("@remix-run/node"); // 显式导入Request和Response const { Request, Response } = node_1; /** @deprecated */ exports.ExpoRequest = Request; /** @deprecated */ exports.ExpoResponse = Response; // 修正笔误 function installGlobals() { (0, node_1.installGlobals)(); global.ExpoRequest = Request; global.ExpoResponse = Response; } exports.installGlobals = installGlobals;
注意:此修改会在下次执行
npm install或yarn install时被覆盖,仅作为临时应急方案。
3. 升级@expo/server包
该问题大概率是@expo/server的已知bug,执行以下命令升级到最新版本:
npm update @expo/server # 或使用yarn yarn upgrade @expo/server
4. 提前执行installGlobals
若无法升级包或Node.js版本,可在项目启动代码最顶部添加以下代码,确保全局对象提前注入:
require('@expo/server/install');
添加后再启动项目,可保证Request/Response被注入后再加载后续模块。
内容的提问来源于stack exchange,提问作者Theo Garrod
相关产品推荐
相关产品推荐

