javascript - 如何修复使用 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
}
解决方案
我改变了响应处理如下。我正在做的这种方法是否正确?如果我错了,请纠正我。
.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));
推荐阅读
- javascript - 将值从一个表格单元格复制到另一个表格单元格也需要背景颜色
- tensorflow - ML:如何创建简单的机器学习模型
- load-balancing - HTTP 请求 -> GSLB 粘性持久性逻辑
- python - 计算熊猫数据框中的距离给出错误
- python - 如何将稀疏矩阵拆分为训练集和测试集?
- bash - 如何在 Bash 上检查网络驱动器上的文件?
- visual-studio-code - 有没有办法以编程方式切换语法突出显示?
- three.js - 三个JS中是否可以有组属性,例如材料属性?
- python - 在课堂上调用函数对我不起作用
- vba - VBA Word 拆分并使用指定名称保存