【发布时间】:2019-08-10 15:54:03
【问题描述】:
我知道这是常见问题,但在获取数据时我不断收到此错误:
SyntaxError: JSON.parse () 中位置 1 处的 JSON 中的意外标记 u
这发生在我测试我的完整代码时,所以我做了测试
res.send(JSON.stringify({"data": "test"}));
在我的客户端,我正在使用以下代码:
fetch(url) // fetch works
.then(checkStatus) // checks for errors, if none send response text
.then(function (responseText) {
let data = JSON.parse(responseText); // where I'm getting the error
在测试值时,我的服务器端的所有内容都会打印正确的值。但是,当我使用 console.log 在客户端打印出 responseText 时,我得到了这个:
f text() { [本机代码] }
为什么会调用这个错误?通过查看堆栈溢出,我了解到当我尝试解析未定义的字符串时会发生此错误。我在解析之前放了一个 if 语句来检查字符串是否未定义:
if (responseText === undefined) {
console.log("responseText is undefined");
}
但是它没有输出,那么字符串真的是未定义的吗?作为旁注,节点是最新的。感谢您的帮助。如果在另一个问题中回答了这个问题,请告诉我。我还没有找到解决这个问题的方法。
编辑:
function checkStatus(response) {
if (response.status >= 200 && response.status < 300) {
return response.text;
} else if (response.status === 404) {
clear();
return Promise.reject(new Error("Sorry, we couldn't find that page"));
} else {
console.log(response.text());
return Promise.reject(new Error(response.status + ": " + response.statusText));
}
}
编辑:response.text 应该是 response.text()。这给了我我的错误。
【问题讨论】:
-
checkStatus究竟在做什么? -
我认为你的问题是
checkStatus函数。它返回以'u'开头的字符串,请console.log(responseText)并显示checkStatus。 -
我在问题中添加了 checkStatus 函数
-
@GrimThor3 谢谢,这更清楚了。我在下面更新了我的答案
标签: javascript node.js json express