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

使用JavaScript调用GPT API时遭遇400错误,请求排查

解决GPT API调用400错误的方案

你的代码里存在几个关键问题,和API key关系不大,主要是API端点、参数配置和逻辑上的错误:

  • 错误的API端点:你用的https://api.openai.com/v1/engines/davinci/jobs是OpenAI的批量任务接口,而调用text-davinci-003应该用补全接口https://api.openai.com/v1/completions。
  • 端点与参数不匹配:jobs接口不需要model参数,补全接口才需要指定对应模型;另外你把prompt写死成了"test prompt",完全没用到用户输入的消息,不符合聊天机器人的逻辑。
  • 缺少错误处理:当API返回400错误时,直接访问data.choices[0].text会导致代码崩溃,必须先判断请求是否成功。

修复后的代码如下:

const chatHistoryContent = document.querySelector("#chat-history-content");
const chatMessageInput = document.querySelector("#chat-message-input");
const chatMessageSubmit = document.querySelector("#chat-message-submit");

chatMessageSubmit.addEventListener("click", async function () {
    const message = chatMessageInput.value.trim();
    if (!message) return; // 空消息不发送
    chatMessageInput.value = "";

    // 添加用户消息到聊天记录
    const userMessageDiv = document.createElement("div");
    userMessageDiv.innerHTML = `You: ${message}`;
    chatHistoryContent.appendChild(userMessageDiv);

    try {
        // 调用API获取回复
        const response = await getResponseFromAPI(message);
        // 添加机器人回复到聊天记录
        const chatbotMessageDiv = document.createElement("div");
        chatbotMessageDiv.innerHTML = `Max: ${response}`;
        chatHistoryContent.appendChild(chatbotMessageDiv);
    } catch (err) {
        console.error("API调用失败:", err);
        const errorDiv = document.createElement("div");
        errorDiv.innerHTML = `Error: ${err.message}`;
        chatHistoryContent.appendChild(errorDiv);
    }
});

async function getResponseFromAPI(message) {
    const apiKey = "sk-myapikey"; // 确保这里是你的有效API Key
    const endpoint = "https://api.openai.com/v1/completions";

    const response = await fetch(endpoint, {
        method: "POST",
        headers: {
            "Content-Type": "application/json",
            "Authorization": `Bearer ${apiKey}`,
        },
        body: JSON.stringify({
            model: "text-davinci-003",
            prompt: message, // 使用用户输入的消息作为prompt
            temperature: 0.5,
            max_tokens: 512,
            top_p: 1,
            frequency_penalty: 0,
            presence_penalty: 0,
        })
    });

    if (!response.ok) {
        const errorData = await response.json();
        throw new Error(errorData.error.message || "请求失败");
    }

    const data = await response.json();
    return data.choices[0].text.trim();
}

额外注意:

  • 确认你的API Key有效且账户有可用额度(可在OpenAI后台查看)
  • 不要在前端代码直接暴露API Key,这会导致密钥泄露,建议把API调用逻辑放到后端服务中。

内容的提问来源于stack exchange,提问作者Max R

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.02 13:46:04