我在使用fetch()到RESTFUL API的客户端上收到一个无效的json响应体错误。
这是我的服务器POST代码,由客户端使用以下代码调用:
.then(conn => {
conn.query("SELECT MAX(`messagesMinute`) FROM `statistics` LIMIT 1;")
.then(rows => { // rows: [ {val: 1}, meta: ... ]
var data = {
'messagesMinuteMAX': Object.values(rows[0])[0] // ugly ass code but i dont know a better way after searching for a while
}
res.json(JSON.stringify(data));
res.end();
})
这是我使用fetch的客户端代码
// Request the highscore of messages per minute
fetch("http://localhost:3001/postRequestMinute", { method: 'GET', headers: {} })
.then((res) => {
return res.json();
})
.then(async (json) => {
console.log(json); // <<<<---- this is the log that retrieves the following
}).catch((err) => {
console.log(err);
});
发送json响应的console.log返回以下内容:
{ "messagesMinuteMAX": 1341 }
这通过多个在线json验证器验证为有效。
我最大的问题是,所有这些都按预期工作,但它还是吐出了这个非常烦人的错误。
不幸的是,这是由于我的代码中另一个不相关的部分。 这是一个无效的问题。 对不起。
也许是你的
res.json(JSON.stringify(data));
这是我在nodejs控制台中所发生的事情
> a = [{ type: 'text', text: 'Hello, world1' }]
[ { type: 'text', text: 'Hello, world1' } ]
> JSON.stringify(JSON.stringify(a))
'"[{\\"type\\":\\"text\\",\\"text\\":\\"Hello, world1\\"}]"'
当你使用两次字符串时,你会在你的对象之外得到两个引号
在fetch API之后,尝试使用json.parse(object_string)希望它对您有用
提示:使用typeof(variable)
验证变量类型
let result
fetch("http://localhost:3001/postRequestMinute", { method: 'GET', headers: {} })
.then((res) => {
console.log(JSON.parse(res))
result = JSON.parse(res)
}).catch((err) => {
console.log(err);
});
不幸的是,这是由于我的代码中另一个不相关的部分。 这是一个无效的问题。 对不起。