尝试从 api 响应访问对象后获取未定义

问题描述 投票:0回答:1

我有一段 JavaScript 代码,可以从 PHP 脚本中获取数据,然后与 OpenAI API 进行通信。 API 响应已成功以 JSON 格式记录在控制台中,但是当我尝试从 JSON 数据访问特定属性时,出现未定义的情况。

我已确认 API 响应结构正确且属性存在。


API Response: {
  "id": "cmpl-8w4TMcnqixeHnrlYCmkhqQaQIQWqi",
  "object": "text_completion",
  "created": 1708850908,
  "model": "gpt-3.5-turbo-instruct",
  "choices": [
    {
      "text": "\nApple is a multinational technology company based in Cupertino, California. It designs and manufactures consumer electronics, computer software, and online services. Some of its most popular products include the iPhone, iPad, Mac computers, and Apple Watch. The company was founded in 1976 by Steve Jobs, Steve Wozniak, and Ronald Wayne and has grown to become one of the largest and most influential companies in the world. It is known for its innovative and user-friendly products and has a strong brand following.",
      "index": 0,
      "logprobs": null,
      "finish_reason": "stop"
    }
  ],
  "usage": {
    "prompt_tokens": 4,
    "completion_tokens": 101,
    "total_tokens": 105
  }
}

这是我的 JavaScript 代码:

document.addEventListener('DOMContentLoaded', function() {
    
 const loader = document.getElementById("svg-loader");
 const loaderFull = document.getElementById("loader");
 const submitBtn = document.getElementById("submitBtn");
 const submitText = document.getElementById("btnText");
 const quizContainer = document.getElementById("quiz-container");
 const shareBtn = document.getElementById("shareBtn");
 const imageContainer = document.getElementById("image-generator");
 

document.getElementById('submitBtn').addEventListener('click', () => {
      quizContainer.classList.add("hidden");
      loaderFull.classList.remove("hidden");
      submitAnswers();
});

function submitAnswers() {

   const prompt = `what is apple?`;
    
    fetch('api/request.php', {
        method: 'POST',
        headers: {
            'Content-Type': 'application/x-www-form-urlencoded',
        },
        body: `prompt=${encodeURIComponent(prompt)}`,
    })
    .then(response => response.text())
    .then(data => {
        console.log('Parsed JSON Data:', JSON.parse(data));
        const jsonData = JSON.parse(data);

            if (data) {
                console.log('API Response:', jsonData);
                
                const resultContainer = document.getElementById('result-container');
                resultContainer.innerHTML = `<p>${jsonData.choices[0].text}</p>`;

        } else {
            console.error('Error: Invalid API response structure');
        }
    })
    .catch(error => {
        console.error('Error:', error);
    })
    .finally(() => {
         loaderFull.classList.add("hidden");
        imageContainer.classList.remove("hidden");
        setTimeout(() => {
           shareBtn.classList.remove("hidden");
        }, 1000);
        
    });
}

});

无论我尝试访问哪个属性,我都无法定义。

javascript php api undefined openai-api
1个回答
0
投票

尝试用以下代码替换这一行

.then(response => response.text())
-

.then(response => response.json())

这会将响应转换为 JSON 格式。您正在转换为文本,因此您未定义。

© www.soinside.com 2019 - 2024. All rights reserved.