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

React.js集成Anthropic messages API遭遇CORS错误求解决方案

React集成Anthropic API的CORS问题解决方案

问题根源

Anthropic的API不支持直接从前端浏览器发起跨域请求,而且绝对不能在前端代码中暴露API Key(会被恶意窃取),CORS报错只是表象,核心是前端直接调用第三方API的安全风险问题。

解决方法

1. 自建后端代理(生产环境推荐)

搭建一个简单的后端服务,由后端转发请求到Anthropic API,前端只请求自己的后端。示例用Node.js/Express实现:

后端代码:

const express = require('express');
const axios = require('axios');
const app = express();
const port = 3001;

app.use(express.json());

// 代理Anthropic消息接口
app.post('/api/anthropic/messages', async (req, res) => {
  try {
    const response = await axios.post(
      'https://api.anthropic.com/v1/messages',
      req.body,
      {
        headers: {
          'x-api-key': process.env.ANTHROPIC_API_KEY, // 从环境变量读取API Key,禁止硬编码
          'anthropic-version': '2023-06-01',
          'Content-Type': 'application/json',
        },
      }
    );
    res.json(response.data);
  } catch (error) {
    res.status(error.response?.status || 500).json(
      error.response?.data || { message: '请求Anthropic API失败' }
    );
  }
});

app.listen(port, () => {
  console.log(`代理服务运行在 http://localhost:${port}`);
});

前端修改请求地址:

try {
  const response = await axios.post(
    'http://localhost:3001/api/anthropic/messages', // 改为代理接口地址
    {
      model: "claude-3-5-sonnet-20240620",
      max_tokens: 1024,
      messages: [
        { "role": "user", "content": "one word" }
      ]
    },
    {
      headers: {
        'Content-Type': 'application/json', // 无需在前端传API Key
      },
    }
  );
  console.log('Model used:', response.data.model);
  return response?.data?.content[0]?.text?.trim(); // 注意Anthropic返回结构是content数组,不是choices
} catch (error) {
  console.error('Error:', error.response ? error.response.data : error.message);
  throw error;
}

2. 开发阶段用框架内置代理

如果用Vite或Create React App,可以直接配置内置代理,避免单独搭后端:

Vite配置(vite.config.js):

import { defineConfig } from 'vite';
import react from '@vitejs/plugin-react';

export default defineConfig({
  plugins: [react()],
  server: {
    proxy: {
      '/api/anthropic': {
        target: 'https://api.anthropic.com/v1',
        changeOrigin: true,
        rewrite: (path) => path.replace(/^\/api\/anthropic/, ''),
        configure: (proxy) => {
          proxy.on('proxyReq', (proxyReq) => {
            proxyReq.setHeader('x-api-key', process.env.ANTHROPIC_API_KEY);
            proxyReq.setHeader('anthropic-version', '2023-06-01');
          });
        },
      },
    },
  },
});

前端请求地址改为/api/anthropic/messages即可,API Key存在项目的.env文件中(如VITE_ANTHROPIC_API_KEY=你的密钥)。

关键提醒

  • 禁止在前端代码中硬编码或通过任何方式暴露API Key,否则会导致密钥泄露,引发账号安全问题。
  • 生产环境必须使用自建后端代理,框架内置代理仅用于开发阶段。

内容的提问来源于stack exchange,提问作者Kshiteej Jain

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.20 22:31:03