JSON bad format in Post method

烂漫一生 提交于 2021-02-11 12:48:53

问题


I'm trying to submit a POST request, but I got error status code 400 because the data I'm sending is in bad format but I don't know how to format that.

The web API expected this format(The web API is working perfectly, if I send the data by Postman I don't have any trouble):

[{ "word": "string", "box": 0 }]

And this is what I am sending:

"["{\"word\": \"Value\", \"box\": 0 }"]"

Any idea how to format it?

This is the entire code simplified:

<form onsubmit="handlePostSubmit()" id="formPost">

  <div>
    <input type="checkbox" id="chk01" name="ckbWord" value="Value" defaultChecked></input>
    <label for="chk01"> value</label>
  </div>

  <button type="submit" form="formPost" value="Submit">Submit</button>
</form>

<script>
function getWords() {
  const words = document.forms[0];
  var txt = "";
  for (var i = 0; i < words.length; i++) {
    if (words[i].checked) {
      txt += '{"word": "' + words[i].value + '", "box": 0 }';
    }
  }
  return txt;
}

function handlePostSubmit() {
//  params.preventDefault();

  const words = getWords();
  alert(words);
  var x = create(words)
            .then(() => {
                //TODO: Msg of ok or error
    alert("Ok")
            });
  alert(x);
}

async function create(params) {
    const response = await fetch("https://localhost:44312/words", {
        method: 'POST',
        headers: {
            'Content-Type': 'application/json',
        },
        body: JSON.stringify([params]),
    });
    if (response.ok) {
        const resposta = await response.json();
        return resposta;
    }
    throw new Error('Error to save words');
}
</script>

回答1:


I think there's no need to use strings to build your JSON.

You can simply push objects, like so:

const wordsFromDoc = document.forms[0]
const words = []
for (var i = 0; i < words.length; i++) {
   if (words[i].checked) {
     words.push({ word: words[i].value, box: 0 });
   }
}

return words;

And then you can just pass those along and JSON.stringify() it later without wrapping it in an array.

const response = await fetch("https://localhost:44312/words", {
    method: 'POST',
    headers: {
        'Content-Type': 'application/json',
    },
    body: JSON.stringify(params),
});



回答2:


Note that you try to make the json string yourself, and that, including a missing , when concating txt is what makes the error. We can fix it but I think you should change the way you implement it.

I recommend using an array instead of concating strings. for example:

function getWords() {
  const words = document.forms[0];
  const wordsArray = [];
  for (var i = 0; i < words.length; i++) {
    if (words[i].checked) {
      wordsArray.push({word: words[i].value, box: 0 });
    }
  }
  return wordsArray;
}

and then later on just perform JSON.stringify(param)



来源:https://stackoverflow.com/questions/63488725/json-bad-format-in-post-method

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!