logo
AI对话
AI写作
AI学术
AI绘画
知识社区

如何通过Node.js和Clash代理访问OpenAI API的详细指南

此对话是使用 海鲸AI 创建的 • 发布时间:2025年06月29日 22:27

我本地连接的clash 做的网络代理 但是现在我通过nodejs 访问openai的接口 还是不通 该如何做

复制问题

Node.js 通过 Clash 代理访问 OpenAI API 解决方案

🔍 问题诊断步骤

1. 首先确认 Clash 代理状态

# 检查 Clash 是否正常运行
curl -x http://127.0.0.1:7890 https://www.google.com
# 或者检查 OpenAI 是否可达
curl -x http://127.0.0.1:7890 https://api.openai.com/v1/models

2. 查看 Clash 配置

  • 确认 HTTP 代理端口(通常是 7890)
  • 确认 SOCKS5 代理端口(通常是 7891)
  • 检查 Clash Dashboard 中的连接状态

💻 Node.js 代理配置方案

方案1:使用 https-proxy-agent(推荐)

安装依赖:

npm install https-proxy-agent http-proxy-agent

代码实现:

const { HttpsProxyAgent } = require('https-proxy-agent');
const { HttpProxyAgent } = require('http-proxy-agent');

// Clash 代理配置
const proxyUrl = 'http://127.0.0.1:7890'; // Clash HTTP 代理端口

// 创建代理 agent
const httpsAgent = new HttpsProxyAgent(proxyUrl);
const httpAgent = new HttpProxyAgent(proxyUrl);

// 方法1:使用 fetch(Node.js 18+)
async function callOpenAI() {
    const response = await fetch('https://api.openai.com/v1/chat/completions', {
        method: 'POST',
        headers: {
            'Authorization': 'Bearer YOUR_API_KEY',
            'Content-Type': 'application/json',
        },
        body: JSON.stringify({
            model: 'gpt-3.5-turbo',
            messages: [{ role: 'user', content: 'Hello!' }]
        }),
        // 重要:配置代理
        agent: httpsAgent
    });
    
    return await response.json();
}

// 方法2:使用 axios
const axios = require('axios');

const apiClient = axios.create({
    baseURL: 'https://api.openai.com/v1',
    headers: {
        'Authorization': 'Bearer YOUR_API_KEY',
        'Content-Type': 'application/json',
    },
    // 配置代理
    httpsAgent: httpsAgent,
    httpAgent: httpAgent,
    proxy: false // 禁用 axios 内置代理,使用 agent
});

async function callOpenAIWithAxios() {
    const response = await apiClient.post('/chat/completions', {
        model: 'gpt-3.5-turbo',
        messages: [{ role: 'user', content: 'Hello!' }]
    });
    
    return response.data;
}

方案2:使用环境变量(全局代理)

设置环境变量:

# Linux/macOS
export HTTP_PROXY=http://127.0.0.1:7890
export HTTPS_PROXY=http://127.0.0.1:7890
export NO_PROXY=localhost,127.0.0.1

# Windows CMD
set HTTP_PROXY=http://127.0.0.1:7890
set HTTPS_PROXY=http://127.0.0.1:7890

# Windows PowerShell
$env:HTTP_PROXY="http://127.0.0.1:7890"
$env:HTTPS_PROXY="http://127.0.0.1:7890"

Node.js 代码:

// 环境变量会被自动识别
const axios = require('axios');

const apiClient = axios.create({
    baseURL: 'https://api.openai.com/v1',
    headers: {
        'Authorization': 'Bearer YOUR_API_KEY',
        'Content-Type': 'application/json',
    }
});

// 直接使用,会自动通过代理
async function callOpenAI() {
    const response = await apiClient.post('/chat/completions', {
        model: 'gpt-3.5-turbo',
        messages: [{ role: 'user', content: 'Hello!' }]
    });
    
    return response.data;
}

方案3:使用 OpenAI 官方库配置代理

npm install openai
const OpenAI = require('openai');
const { HttpsProxyAgent } = require('https-proxy-agent');

const openai = new OpenAI({
    apiKey: 'YOUR_API_KEY',
    httpAgent: new HttpsProxyAgent('http://127.0.0.1:7890'),
});

async function main() {
    const completion = await openai.chat.completions.create({
        messages: [{ role: 'user', content: 'Hello!' }],
        model: 'gpt-3.5-turbo',
    });

    console.log(completion.choices[0]);
}

🛠️ 完整的调试方案

1. 创建测试脚本

// test-proxy.js
const { HttpsProxyAgent } = require('https-proxy-agent');
const axios = require('axios');

async function testProxy() {
    const proxyUrl = 'http://127.0.0.1:7890';
    const agent = new HttpsProxyAgent(proxyUrl);
    
    console.log('🔍 测试代理连接...');
    
    try {
        // 测试1:检查代理是否工作
        console.log('1. 测试 Google 连接...');
        const googleResponse = await axios.get('https://www.google.com', {
            httpsAgent: agent,
            timeout: 10000
        });
        console.log('✅ Google 连接成功');
        
        // 测试2:检查 OpenAI API 连接
        console.log('2. 测试 OpenAI API 连接...');
        const openaiResponse = await axios.get('https://api.openai.com/v1/models', {
            headers: {
                'Authorization': 'Bearer YOUR_API_KEY' // 替换为你的 API Key
            },
            httpsAgent: agent,
            timeout: 10000
        });
        console.log('✅ OpenAI API 连接成功');
        console.log('可用模型数量:', openaiResponse.data.data.length);
        
    } catch (error) {
        console.error('❌ 连接失败:', error.message);
        console.error('错误详情:', error.code);
    }
}

testProxy();

2. 运行测试

node test-proxy.js

🔧 常见问题解决

问题1:端口号错误

// 检查 Clash 配置中的端口号
const commonPorts = [7890, 7891, 8080, 1080];

async function findWorkingPort() {
    for (const port of commonPorts) {
        try {
            const agent = new HttpsProxyAgent(`http://127.0.0.1:${port}`);
            await axios.get('https://www.google.com', { httpsAgent: agent, timeout: 5000 });
            console.log(`✅ 工作端口: ${port}`);
            return port;
        } catch (error) {
            console.log(`❌ 端口 ${port} 不可用`);
        }
    }
}

问题2:Clash 规则配置

确保 Clash 配置文件包含 OpenAI 规则:

rules:
  - DOMAIN-SUFFIX,openai.com,PROXY
  - DOMAIN-SUFFIX,api.openai.com,PROXY
  - DOMAIN-KEYWORD,openai,PROXY

问题3:SSL/TLS 问题

// 如果遇到 SSL 证书问题,临时解决方案(不推荐生产环境)
process.env["NODE_TLS_REJECT_UNAUTHORIZED"] = 0;

// 或者配置自定义 CA
const https = require('https');
const agent = new https.Agent({  
    rejectUnauthorized: false
});

📋 完整工作示例

// openai-with-clash.js
const axios = require('axios');
const { HttpsProxyAgent } = require('https-proxy-agent');

class OpenAIWithProxy {
    constructor(apiKey, proxyUrl = 'http://127.0.0.1:7890') {
        this.apiKey = apiKey;
        this.proxyUrl = proxyUrl;
        this.agent = new HttpsProxyAgent(proxyUrl);
        
        this.client = axios.create({
            baseURL: 'https://api.openai.com/v1',
            headers: {
                'Authorization': `Bearer ${apiKey}`,
                'Content-Type': 'application/json',
            },
            httpsAgent: this.agent,
            timeout: 30000
        });
    }
    
    async testConnection() {
        try {
            const response = await this.client.get('/models');
            console.log('✅ OpenAI API 连接成功');
            return true;
        } catch (error) {
            console.error('❌ OpenAI API 连接失败:', error.message);
            return false;
        }
    }
    
    async chat(messages, model = 'gpt-3.5-turbo') {
        try {
            const response = await this.client.post('/chat/completions', {
                model,
                messages,
                max_tokens: 1000
            });
            
            return response.data;
        } catch (error) {
            console.error('Chat API 调用失败:', error.response?.data || error.message);
            throw error;
        }
    }
}

// 使用示例
async function main() {
    const openai = new OpenAIWithProxy('YOUR_API_KEY');
    
    // 测试连接
    const isConnected = await openai.testConnection();
    if (!isConnected) {
        console.log('请检查代理设置和 API Key');
        return;
    }
    
    // 发送聊天请求
    try {
        const result = await openai.chat([
            { role: 'user', content: 'Hello, how are you?' }
        ]);
        
        console.log('AI 回复:', result.choices[0].message.content);
    } catch (error) {
        console.error('聊天失败:', error.message);
    }
}

main();

🚀 快速启动步骤

  1. 确认 Clash 运行状态
  2. 安装必要依赖:
    npm install axios https-proxy-agent
    
  3. 使用上面的完整示例代码
  4. 替换 YOUR_API_KEY 为你的实际 API Key
  5. 运行测试

如果还有问题,请告诉我:

  1. 你的 Clash 代理端口号
  2. 具体的错误信息
  3. 你使用的 Node.js 版本

我会为你提供更精确的解决方案!

重新生成
语音播放
复制回答