how to solve "value_error.jsondecode" when fetch POST?

79 views Asked by At

here my full code before the question,

async function fetchApi() {
  const options = {
    method: "POST",
    headers: {
      Authorization: auth,
      "Content-Type": "application/json",
    },
    body: '{"seed":"12345","Prompt":"Text prompt"}',
  }

  try {
    const response = await fetch(url, options);
    const data = await response.json();
    console.log(data);
  } catch (error) {
    console.error(error);
  }
}

i'm trying to fetch API with POST method, but I have a problem with the body

The API provider use this code by default

body: '{"seed":"12345","prompt":"Text prompt"}'

when I change with multi-line like this

body: {
‎ ‎ ‎ ‎ ‎ seed: "12345",
‎ ‎ ‎ ‎ ‎ ‎prompt: "Text prompt"
}

the console.log show error

"value_error.jsondecode"

I want to add input.value, like this

body: {
"seed" : inputSeed.value;
"Prompt" : inputPrompt.value;
}

but it can't be done in the inline JSON code,

maybe not the inline JSON, but the body itself why contain apostrophe, when in fact it should start with a semicolon

body: {}

not

body: '{}'
1

There are 1 answers

0
Quentin On

You have two different problems, but multiple lines is not one of them.

  • You have passed fetch an object instead of a string of JSON
  • Property names in JSON must be quoted, and you have removed the quotes from around seed and prompt.

I want to add input.value, but it can't be done in the inline JSON code,

JavaScript has a function to convert an object to JSON.