Node.js中如何使用需import的http-proxy-agent模块?
解决Node.js中http-proxy-agent模块的引入问题
情况1:使用ES模块(import语法)
你遇到的SyntaxError: Cannot use import statement outside a module错误,是因为Node.js默认将.js文件视为CommonJS模块处理。要使用ES模块的import语法,需做如下配置:
- 在项目根目录的
package.json中添加"type": "module"字段:{ "type": "module" } - 配置完成后,即可正常使用
import引入模块:import { HttpProxyAgent } from 'http-proxy-agent';
情况2:使用CommonJS模块(require语法)
出现TypeError: createHttpProxyAgent is not a function错误,是因为http-proxy-agent的CommonJS导出采用默认导出而非命名导出,正确的引入方式为:
const { HttpProxyAgent } = require('http-proxy-agent'); // 若上述方式仍报错,尝试获取默认导出: const HttpProxyAgent = require('http-proxy-agent').default;
验证使用示例
无论采用哪种引入方式,都可以按以下方式创建代理实例并使用:
// 示例代理地址:http://localhost:8080 const agent = new HttpProxyAgent('http://localhost:8080'); // 将agent用于HTTP请求(以http模块为例) const http = require('http'); // 或使用ES模块语法:import http from 'http'; http.get('http://example.com', { agent }, (res) => { // 处理响应逻辑 });
内容的提问来源于stack exchange,提问作者Raol mAX
相关产品推荐
相关产品推荐

