首页 > 解决方案 > 如何修复使用 fetch 向服务器发送 POST 请求时抛出的“JSON 输入意外结束”?

问题描述

我有一个简单的聊天框 UI,它集成到使用 .netcore 开发的聊天机器人中。

SyntaxError:JSON 输入意外结束
(匿名)@im.html:201

在与机器人进行了几次对话后,我被这个错误所困扰。下面是我用来捕获文本消息的输入框。

<form action="javascript:void(0);" class="bg-light" autocomplete="off">
  <div class="input-group">
    <input type="text" placeholder="Type a message" aria-describedby="button-addon2" class="form-control rounded-0 border-0 py-4" id="message">
    <div class="input-group-append">
      <button id="button-addon2" type="submit" class="btn btn-link" onclick="userMessage()"> <i class="fa fa-paper-plane"></i></button>
    </div>
  </div>
</form>

当用户按下回车键时,我会在 UI 中显示键入的消息并向服务器发送 POST 请求以获取响应。

 // User message layout
function userMessage() {
    var spinner = document.getElementById('textSpinner');
    var h5 = document.getElementById("h5");
    var inputBox = document.getElementById("message");
    var p = document.createElement("p");
    var inputValue = inputBox.value;
    var text = document.createTextNode(inputValue);
    p.appendChild(text);

    if (inputValue === '' || !h5.innerText) {
        alert("Please sart the session first!");
    } else {
        var div = document.createElement("div");
        div.className = "media";

          /.../

        var chatArea = document.getElementById('chat-area')
        chatArea.scrollIntoView({ behavior: 'smooth', block: 'end' })
        spinner.style.display = "none";
        interact(h5.innerText, inputValue);
    }
    inputBox.value = "";
}

下面是 POST 请求

   // POST user message
   function interact(userId, message) {
    var spinner = document.getElementById('textSpinner');
    spinner.style.display = "block";
    const payload = {
        userId: userId,
        utterance: message
    };

    fetch('Sessions/Interact', {
        method: 'POST',
        headers: {
            'Accept': 'application/json',
            'Content-Type': 'application/json'
        },
        body: JSON.stringify(payload)
    })
        .then(response => response.json())
        .then(data => botMessage(data.Message))
        .then(() => spinner.style.display = "none")
        .catch(error => console.error(error));
    }

当我从服务器获得响应时,我正在调用另一个函数botMessage(),该函数类似于userMessage()将显示机器人消息的函数。有人可以指导我为什么会引发此错误,是否有任何解决方案可以解决此问题?提前致谢。

这是来自服务器的响应正文。

{
  "Message": "Hello, It's me. Let's start chatting shall we?",
  "Data": null
}

标签: javascripthtmlfetch

解决方案


我改变了响应处理如下。我正在做的这种方法是否正确?如果我错了,请纠正我。

.then(response => {
      if (response.status === 200) {
         return response.json()
         .then(data => botMessage(data.Message))
      } else if (response.status === 204) {
         return;
      }
    })           
    .then(() => spinner.style.display = "none")
    .catch(error => console.error(error));

推荐阅读