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>