400 Error, pleaassee help :D

Ok, here’s the code. I’m a newbie guys, so please go easy on me lol

generateButton = document.getElementById("generate-button");
generateButton.addEventListener("click", function() {
  // Get the value of the "idea" element
  var idea = document.getElementById("idea").value;
  // Make a request to the OpenAI API using the `fetch` method
  fetch('https://api.openai.com/v1/completions', {
    method: 'POST',
    headers: {
      'Content-Type': 'application/json',
      'Authorization': 'Bearer sk-'
    body: JSON.stringify({
      "engine": "text-davinci-003",
      "prompt": idea,
      "max_tokens": 256,
      "temperature": 0.5,
    .then((response) => {
    .then((data) => {
      // Set the value of the "copy" element to the generated text
      document.getElementById("copy").value = data.choices[0].text;

I keep getting a 400 error over and over.

I have this exact issue and there does not seem to be a solution anywhere, Does Openai plan on giving us a solution to this?

Are you actually putting the API key in?

  const headers = {
    'Authorization': `Bearer ${process.env.OPENAI_SECRET_KEY}`,

You might also try a javascript API wrapper to make it easier.

A 400 error means there’s something wrong with your request.

While I don’t know the answer, and I’m not an expert on using fetch, I think your issue is related to CORS (Cross origin Request)

I suspect it is being triggered by the API key being in the header (which you actually need)
The content-type of JSON may also be an issue

Here is a useful article Fetch: Cross-Origin Requests

I also found this:

If it is actually a cross original request issue, you could setup a cors proxy on your machine

Search for the following snippet in the page (cant link direct):

npm install -g local-cors-proxy

I don’t know the implications of this on a hosted server. I’m just trying to give you ideas as no-one else seems to have a solution

1 Like

Yeah, that sounds like it might be it.

An API wrapper would likely solve the problem too.

I bet it’s because the API key would be displayed on the frontend javascript - ie not secure?

1 Like

Hey guys, I too am seeing a 400 bad request error for just some of my requests. For the first few requests, it works. But once I get a long response, and I append that as part of the prompt it no longer works. Is there some sort of limit to the prompt length?