"Encountered a 400 Error while trying to access the OpenAI

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))
.

Answer №1

To resolve the issue, I successfully resolved it by sending the object through

openairequest.send(JSON.stringify(payload))
. Additionally, I updated from using an outdated text model to the recommended gpt-3.5-turbo-instruct. The solution I implemented was discovered on freecodecamp.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Interfacing with Web Services using C# GUI

Currently, I am running a web service on a local server which includes a method that generates a JSON representation of an Oracle database query converted from a List<Dictionary<String, String>> object. However, my GUI program also requires th ...

Retrieve information from two tables in mySQL and merge them together

When trying to select data from two tables in my database - comments and users, I encountered an issue. The structure of these tables is as follows: comments: commentID | commentDateAndTime | imageID | userID | comment users: userID | username My goal ...

Troubles encountered while parsing nested JSON objects with a streaming parser

I'm currently using the code provided in this helpful resource for parsing my JSON: Although it successfully handles most of the JSON data I have, it encounters issues when a JSON object is directly nested as a child within another one. To illustrat ...

Error: The function this.saveAlpha is not recognized in the current context at eval

This code features a start button, stop button, and a timer. The goal is to retrieve information from the phone using events like DeviceOrientationEvent, which includes properties such as absolute, alpha, beta, and gamma (referenced in this link: here). I& ...

Is there a way to incorporate a fade-in effect when I trigger the expand function in this script?

I recently came across a jQuery plugin for expanding and collapsing content. I am interested in adding a fade-in effect to this plugin specifically when the EXPAND button is clicked. How can I accomplish this? $(document).ready(function () { var maxlines ...

Inserting data into a JavaScript database

When attempting to add a new row to a datatable and submit it to a JSP for database insertion, an error is encountered. The error message reads: "You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the r ...

The jQuery $.ajax request is still in a pending state

I've developed a straightforward chat application that utilizes the long-polling method with jQuery. function sendchat(){ // This function sends the message $.ajax({ url: "send.php", async: true, data: { /* insert inputbox1.value */ }, succe ...

No security hurdles detected - Volley

Greetings! I am currently utilizing volley for parsing my API. Whenever I provide valid credentials, everything works smoothly and I receive an auth token. However, in the case of incorrect credentials, I still wish to parse the response. Instead, I am enc ...

Sending json data to an MVC controller

I am attempting to send data using jQuery ajax to an Asp.Net MVC controller. The class I am using is as follows: public class InnerStyle { [JsonProperty("color")] public string HeaderColor { get; set; } [JsonProperty("font-size")] publ ...

Each time guildMemberAdd is triggered in Discord.js, it may not run consistently

At times, I am left baffled by the inconsistency in behavior of this code. Sometimes it works like a charm, while other times it refuses to add people for hours on end, only to randomly start working again. Any suggestions on how I can resolve this issue? ...

Having trouble accessing the href attribute after clicking on an <a> tag with JavaScript

My issue lies in retrieving the href attribute of <a> tags when there is another element nested inside them: Here's the code snippet: const $elems = document.querySelectorAll('.content-container a') var elems = Array.from($elems) e ...

generate dynamic custom headers in an express application for accessibility by an Angular application

https://i.stack.imgur.com/6jyNE.pngRecently, I have started using Express and despite my extensive research, I haven't been able to find a solution to my issue. The problem is that I am receiving headers in my Express app, but when I attempt to make t ...

Tips on implementing two ng-repeat directives within a specific element

Inside a JSON file, there is an array that needs to be iterated within <td> tags. The functionality entails creating a table based on user input, which includes the number of rows, input columns, and output columns provided by the user. Three arrays ...

What is the best way to transfer a variable from a Node.js Express server to an EJS HTML file in order to toggle alert visibility?

Hello, I am currently facing a challenge in sending a variable from my app.js file to my ejs HTML file in order to toggle the display of an alert. Here is what the relevant part of my app.js code looks like: view image description here Initially, I attem ...

Unauthorized access for POST request in WooCommerce API: 401 error

Let's start by examining the complete code to better understand the issue at hand. Here is the WooCommerce API authentication using the consumer key and secret from the file checkout.ts: this.WooCommerce = WC({ url:"http://localhost/ ...

Error: Attempting to access property of undefined variable

I have searched for similar titles related to my issue, but I still haven't found a solution. The error I am encountering when clicking on agent_dashboard on the side panel is as follows: txtDisplayName = <div style="border:1px solid #990000;paddi ...

Is it possible to utilize Babel for transpiling, importing, and exporting in the client, all without relying on Web

Is it possible to compile JSX and export variables through the global namespace using Babel? I'm not interested in setting up a Webpack server. I'm currently familiarizing myself with ES6, JSX, Babel, and React, and I find adding another librar ...

Adjusting the content within a text area using an AngularJS service

I am currently editing text in a textarea within the admin view and I would like to display it through an angular service on the user view. However, I want the text to be displayed in multiple rows, maintaining the same format that I entered in the textare ...

What are some ways to enhance the speed of my canvas animations?

My code generates imagedata and places it in a canvas. However, when I expand the window size, the rendering slows down significantly. Is there a way to optimize this for smooth operation in fullscreen mode, even though it might seem naive? What would be ...

Utilizing NextJS Image Component in Conjunction with Auth0

I have been working on integrating auth0 with nextJS and encountered an issue with the next.js Image component. Let's review the code snippet: import Image from "next/image" import { useUser } from "@auth0/nextjs-auth0" export def ...