Next.js+TypeScript调用Mailchimp API ping.get()遇TypeError求助
问题:Next.js + TypeScript调用Mailchimp API触发TypeError错误
我在使用Next.js结合TypeScript开发时,按照Mailchimp官方API文档示例调用mailchimp.ping.get()函数,却触发了TypeError: Cannot read properties of undefined (reading '0')错误。
我的代码
import { NextRequest, NextResponse } from "next/server"; const mailchimp = require('@mailchimp/mailchimp_marketing'); const api_key = process.env.MAILCHIMP_API_KEY; mailchimp.setConfig({ apiKey: api_key, server: 'us18', }); export async function POST(request: NextRequest) { try { const response = await mailchimp.ping.get(); if (response && response.health_status) { console.log(response.health_status); } else { console.error('Unexpected response:', response); } } catch (error) { console.error('Error:', error); } return NextResponse.json('Successfully added to the waitlist!'); }
报错信息
Error: TypeError: Cannot read properties of undefined (reading '0') at isInsideNodeModules (node:internal/util:511:17) at showFlaggedDeprecation (node:buffer:178:8) at new Buffer (node:buffer:266:3) at encoder (webpack-internal:///(rsc)/./node_modules/superagent/lib/node/index.js:498:12) at RequestBase._auth (webpack-internal:///(rsc)/./node_modules/superagent/lib/request-base.js:431:44) at Request.auth (webpack-internal:///(rsc)/./node_modules/superagent/lib/node/index.js:501:15) at exports.callApi (webpack-internal:///(rsc)/./node_modules/@mailchimp/mailchimp_marketing/src/ApiClient.js:396:13) at module.exports.getWithHttpInfo (webpack-internal:///(rsc)/./node_modules/@mailchimp/mailchimp_marketing/src/api/PingApi.js:65:27) at module.exports.get (webpack-internal:///(rsc)/./node_modules/@mailchimp/mailchimp_marketing/src/api/PingApi.js:77:17) at POST (webpack-internal:///(rsc)/./src/app/api/add-mailing-contact/route.ts:33:47) at /Users/mykal/Documents/kurie/kurie-homepage/node_modules/next/dist/compiled/next-server/app-route.runtime.dev.js:6:55044
期望的正常响应
{ "health_status": "Everything's Chimpy!" }
解决方法
这个错误的根源是Mailchimp官方SDK依赖的superagent库,在Next.js App Router的RSC(React Server Components)运行环境中调用Node.js的Buffer API时出现兼容性问题。以下是几种可行的解决方案:
方案1:改用Edge Runtime
在API路由文件顶部添加export const runtime = 'edge';,切换到Edge Runtime,它对Node.js API的兼容逻辑更适配:
import { NextRequest, NextResponse } from "next/server"; export const runtime = 'edge'; // 添加该行 const mailchimp = require('@mailchimp/mailchimp_marketing'); const api_key = process.env.MAILCHIMP_API_KEY; mailchimp.setConfig({ apiKey: api_key, server: 'us18', }); export async function POST(request: NextRequest) { // 原有代码保持不变 }
方案2:直接使用Fetch调用API,规避SDK依赖
放弃官方SDK,直接通过原生fetch调用Mailchimp的Ping API,完全绕开兼容性问题:
import { NextRequest, NextResponse } from "next/server"; export async function POST(request: NextRequest) { const apiKey = process.env.MAILCHIMP_API_KEY; const serverPrefix = 'us18'; // 替换为你的Mailchimp服务器前缀 try { // Mailchimp授权规则:用户名任意,密码为API Key const authHeader = `Basic ${Buffer.from(`any:${apiKey}`).toString('base64')}`; const response = await fetch(`https://${serverPrefix}.api.mailchimp.com/3.0/ping`, { method: 'GET', headers: { 'Authorization': authHeader, 'Content-Type': 'application/json' } }); if (!response.ok) { throw new Error(`请求失败,状态码:${response.status}`); } const data = await response.json(); console.log(data.health_status); return NextResponse.json('Successfully added to the waitlist!'); } catch (error) { console.error('Error:', error); return NextResponse.json({ error: 'Ping Mailchimp失败' }, { status: 500 }); } }
方案3:降级到Pages Router
如果项目允许,将API路由迁移到Next.js的Pages Router(pages/api/目录下),该环境对Node.js API的支持更完善,官方SDK可正常运行。
内容的提问来源于stack exchange,提问作者Michael Han
相关产品推荐
相关产品推荐

