Search code examples
javascriptopenai-apigpt-3

OpenAI ChatGPT API: CORS policy error when fetching data


I am trying to write a simple JavaScript script which uses the ChatGPT API to ask a question and get a response.

However I am getting the following error message:

"Access to fetch at 'https://api.chatgpt.com/answer?question=How%20are%20you?&api_key=sk-U3BPK...' from origin 'https://wordpress-......cloudwaysapps.com' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource. If an opaque response serves your needs, set the request's mode to 'no-cors' to fetch the resource with CORS disabled."

I have enabled CORS headers server side in my hosting environment. But the error remains.

What is the reason for this issue and how can I fix this issue?

Here is my code:

<html>
<head>
  <script>
    function askQuestion() {
      var question = document.getElementById("questionInput").value;
      var apiKey = document.getElementById("apiKey").value;
      // access chatgpt's API and pass in the question and API key as parameters
      fetch("https://api.chatgpt.com/answer?question=" + question + "&api_key=" + apiKey)
        .then(response => {
          if (!response.ok) {
            throw new Error("Failed to fetch answer from API");
          }
          return response.json();
        })
        .then(data => {
          // get the answer from the API response and display it in the textbox
          document.getElementById("answerBox").value = data.answer;
        })
        .catch(error => {
          console.error("Error fetching answer from API: ", error);
        });
    }

    function askFollowUpQuestion() {
      var followUpQuestion = document.getElementById("followUpQuestionInput").value;
      var apiKey = document.getElementById("apiKey").value;
      // access chatgpt's API and pass in the follow-up question and API key as parameters
      fetch("https://api.chatgpt.com/answer?question=" + followUpQuestion + "&api_key=" + apiKey)
        .then(response => {
          if (!response.ok) {
            throw new Error("Failed to fetch answer from API");
          }
          return response.json();
        })
        .then(data => {
          // get the answer from the API response and display it in the textbox
          document.getElementById("followUpAnswerBox").value = data.answer;
        })
        .catch(error => {
          console.error("Error fetching answer from API: ", error);
        });
    }
  </script>
</head>
<body>
  <input type="text" id="questionInput" placeholder="Enter your question here"></input>
  <br>
  <input type="text" id="apiKey" placeholder="Enter your API key"></input>
  <br>
  <button onclick="askQuestion()">Ask</button>
  <br>
  <textarea id="answerBox" readonly></textarea>
  <br>
  <input type="text" id="followUpQuestionInput" placeholder="Enter your follow-up question here"></input>
  <br>
  <button onclick="askFollowUpQuestion()">Ask Follow-up</button>
  <br>
  <textarea id="followUpAnswerBox" readonly></textarea>
</body>
</html>

Solution

  • UPDATE: 1 March 2023

    ChatGPT API (i.e., Chat completions API) is now available

    As stated in the official OpenAI blog:

    ChatGPT and Whisper models are now available on our API, giving developers access to cutting-edge language (not just chat!) and speech-to-text capabilities. Through a series of system-wide optimizations, we’ve achieved 90% cost reduction for ChatGPT since December; we’re now passing through those savings to API users. Developers can now use our open-source Whisper large-v2 model in the API with much faster and cost-effective results. ChatGPT API users can expect continuous model improvements and the option to choose dedicated capacity for deeper control over the models. We’ve also listened closely to feedback from our developers and refined our API terms of service to better meet their needs.

    See the documentation.


    ChatGPT API is not available yet

    As stated on the official OpenAI Twitter profile:

    We've learned a lot from the ChatGPT research preview and have been making important updates based on user feedback. ChatGPT will be coming to our API and Microsoft's Azure OpenAI Service soon.

    Did you mean the GPT-3 API? If yes, then read the documentation, see the list of all available GPT-3 models, and learn how to write the code using the Completions endpoint.