You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

使用Next.js TypeScript调用Claude API报错,控制台显示正常

Claude API调用持续报错排查(Next.js TypeScript环境)

我使用Next.js + TypeScript + Anthropic SDK开发时,调用Claude API一直报错。Anthropic控制台显示API状态正常,且每次点击调用按钮都会生成调用日志。我严格遵循官方文档步骤实现,尝试了多种route.ts写法、确认路径无误,甚至用axios直接在前端调用,问题依然存在。

前端组件代码(ClaudeInteraction.tsx)

"use client";
import React, { useState } from "react";
import { Button } from "@/components/ui/button";

export default function ClaudeInteraction() {
    const [responseText, setResponseText] = useState<string>("");

    const handleSubmit = async () => {
        try {
            const response = await fetch("/api/claude-api", {
                method: "POST",
                headers: {
                    "Content-Type": "application/json",
                },
                body: JSON.stringify({ message: "Hello there" }),
            });

            if (!response.ok) {
                throw new Error("Failed to get response from Claude API");
            }

            const data = await response.json();
            setResponseText(data.text);
        } catch (error) {
            console.error("Error getting response from Claude:", error);
            setResponseText("Error: Unable to get response from Claude.");
        }
    };

    return (
        <div className="text-white">
            <Button onClick={handleSubmit}>Send Request to Claude</Button>
            {responseText && <div>Response: {responseText}</div>}
        </div>
    );
}

API路由代码

import { NextApiRequest, NextApiResponse } from 'next';
import Anthropic from '@anthropic-ai/sdk';

const client = new Anthropic({ apiKey: process.env.ANTHROPIC_API_KEY });

export async function POST(req: NextApiRequest, res: NextApiResponse) {
    const { message } = req.body;

    try {
        const result = await client.messages.create({
            messages: [
                {
                    role: 'user',
                    content: "Hello there",
                },
            ],
            model: 'claude-3-haiku-20240307',
            max_tokens: 100,
        });
        res.status(200).json({ text: result.content });
    } catch (error) {
        console.error('Error fetching response:', error);
        res.status(500).json({ error: 'Error fetching response' });
    }
}

排查建议

  • 确认API密钥有效性:检查.env.local中ANTHROPIC_API_KEY是否正确配置,可在API路由中添加console.log(process.env.ANTHROPIC_API_KEY)验证读取状态,同时确认密钥未过期、具备调用指定模型的权限。
  • 修正响应内容解析:Anthropic SDK返回的result.content是数组类型(结构为[{type: "text", text: "响应内容"}]),直接返回会导致前端解析异常,应修改为res.status(200).json({ text: result.content[0].text })。
  • 打印完整错误详情:在API路由的catch块中,将错误转为JSON格式打印,比如console.error('Anthropic API Error:', JSON.stringify(error, null, 2)),获取具体错误原因(如权限不足、模型参数错误等)。
  • 匹配Next.js路由模式:如果使用App Router,API路由文件应放在app/api/claude-api/route.ts,且需使用NextRequest和NextResponse而非NextApiRequest/NextApiResponse;如果是Pages Router,文件应放在pages/api/claude-api.ts。
  • 验证基础接口连通性:先写一个返回固定内容的测试API接口,确认前端能正常接收响应,排除路由、CORS等非Claude SDK相关问题。
  • 检查请求参数合法性:确认model参数拼写正确,max_tokens值在允许范围内,消息格式符合Anthropic API要求。

内容的提问来源于stack exchange,提问作者Easton Raboin

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.23 05:35:09