【问题标题】:JSON bad format in Post methodPost 方法中的 JSON 格式错误
【发布时间】:2020-08-19 14:02:40
【问题描述】:

我正在尝试提交 POST 请求,但我收到错误状态代码 400,因为我发送的数据格式错误,但我不知道如何格式化。

Web API 需要这种格式(Web API 工作正常,如果我通过 Postman 发送数据就没有任何问题):

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

这就是我要发送的内容:

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

知道如何格式化吗?

这是整个代码的简化:

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

【问题讨论】:

  • 你为什么要这样做body: JSON.stringify([params]),而不是body: JSON.stringify(params),
  • 编写自己的 json 生成方法是一个直接的危险信号。绝对没有理由这样做。
  • 在不久的将来我会发送这样的数据:[ { "word": "string", "box": 0 }, { "word": "string2", "box": 0 } ] 但我不认为这是问题,不是吗?
  • 我正在尝试自己处理代码,但您调用的 api 似乎对公众不可用。即:本地主机:44312。你有这个 API 的公开版本吗?

标签: javascript http-post http-status-code-400


【解决方案1】:

我认为没有必要使用字符串来构建您的 JSON。

您可以像这样简单地推送对象:

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;

然后您可以将它们传递给 JSON.stringify() 稍后再传递,而无需将其包装在数组中。

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

【讨论】:

  • 这里的重点是我不知道如何使用 javascript 发送对象而不是字符串。所以,它就像一个魅力,谢谢!
【解决方案2】:

请注意,您尝试自己制作 json 字符串,并且在连接 txt 时包含缺少的 , 是导致错误的原因。 我们可以修复它,但我认为您应该改变实现方式。

我建议使用数组而不是连接字符串。例如:

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;
}

然后再执行JSON.stringify(param)

【讨论】:

    猜你喜欢
    • 2020-08-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-05-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多