var openairequest = new XMLHttpRequest();
const payload = ({
"model": "text-davinci-003",
"prompt": "say this is a test"
});
console.log(payload)
openairequest.open("POST",`https://api.openai.com/v1/completions?data=${encodeURIComponent(JSON.stringify(payload))}`)
openairequest.setRequestHeader("Content-Type", "application/json");
openairequest.setRequestHeader("Authorization",`Bearer ${open_ai_key}`)
I decided to test the XHR request to the OpenAI API completions URL to ensure everything was functioning correctly.
{
"error": {
"message": "You didn't provide an API key. You need to provide your API key in an Authorization header using Bearer auth (i.e. Authorization: Bearer YOUR_KEY), or as the password field (with blank username) if you're accessing the API from your browser and are prompted for a username and password. You can obtain an API key from https://platform.openai.com/account/api-keys.",
"type": "invalid_request_error",
"param": null,
"code": null
}
}
The response I received was unexpected, stating that an API key wasn't provided even though I believed I passed a JSON object.
EDIT Upon further examination, I realized I hadn't actually sent the request. After rectifying this issue, I still couldn't pinpoint the problem with how I included the API Key for authorization.
var open_ai_key = "MY KEY"
var openairequest = new XMLHttpRequest();
const payload = ({
"model": "text-davinci-003",
"prompt": "say this is a test"
});
openairequest.open("POST",`https://api.openai.com/v1/completions?data=${encodeURIComponent(JSON.stringify(payload))}`)
openairequest.setRequestHeader("Content-Type", "application/json");
openairequest.setRequestHeader("Authorization",`Bearer ${open_ai_key}`)
openairequest.send()
console.log(openairequest)
EDIT
To resolve the issue, I made sure to send the object through
openairequest.send(JSON.stringify(payload))
.