使用Stripe时触发Uncaught (in promise) TypeError: http.Agent is not a constructor错误
问题
尝试使用Stripe服务时,运行以下代码触发了Uncaught (in promise) TypeError: http.Agent is not a constructor错误。
代码示例
import Stripe from 'stripe'; const stripe = new Stripe('<my test key>', { apiVersion: '2022-11-15', });
报错信息
Uncaught (in promise) TypeError: http.Agent is not a constructor at node_modules/stripe/lib/net/NodeHttpClient.js (NodeHttpClient.js:6:26) at __require2 (chunk-NNYXQWFV.js?v=619287ea:19:50) at Stripe.createNodeHttpClient (stripe.js:117:28) at new Stripe (stripe.js:89:44) at myStripe (stripe.ts:8:20) at [lessonid].vue:189:5 at runtime-core.esm-bundler.js:2723:40 at callWithErrorHandling (runtime-core.esm-bundler.js:155:22) at callWithAsyncErrorHandling (runtime-core.esm-bundler.js:164:21) at hook.__weh.hook.__weh (runtime-core.esm-bundler.js:2697:29)
运行环境
Node ^17.0.0 stripe ^11.3.0 MacOS Typescript
解决方案
这个错误的核心原因是你把仅适用于Node.js环境的Stripe后端SDK,放到了浏览器(Vue前端)环境中执行——http.Agent是Node.js的内置模块,浏览器里不存在这个对象。
解决办法如下:
- 迁移到后端执行:把Stripe的初始化和所有API调用代码,移到你的Node.js后端服务里。前端通过调用后端提供的API接口,间接和Stripe交互,确保密钥(secret key)不会暴露在前端。
- 前端改用专用SDK:如果需要在前端处理Stripe相关操作(比如支付按钮),安装并使用Stripe的前端专用SDK
@stripe/stripe-js:
前端初始化示例:npm install @stripe/stripe-js
注意:前端只能使用可发布密钥(publishable key),测试密钥(secret key)必须严格保存在后端,绝对不能出现在前端代码中。import { loadStripe } from '@stripe/stripe-js'; const stripe = await loadStripe('<你的可发布密钥>'); - 排查打包配置:检查你的构建工具(Vite/Webpack等)配置,确保Stripe后端SDK没有被错误打包到前端代码里,区分好前后端代码的编译范围。
内容的提问来源于stack exchange,提问作者user16525780
相关产品推荐
相关产品推荐

