[英]error when trying to fetch data from server Parsing error: Unexpected token
[英]React fetch from Go/Golang server parsing data in unexpected JSON format to number
我正在构建一个 web 应用程序,它使用 Go 服务器向 React 应用程序提供数据。
在我的服务器的构建中,我遵循了 Go 文档( https://golang.org/doc/tutorial/web-service-gin )提供的教程。 我的代码与该代码非常相似,当我使用curl时,我得到了预期的结果。
[
{
"id":0,
"date":"2021-11-21T12:00:00Z",
"rentedTo":"Bob",
"rentedBy":"Jim"
},
//etc...
然而,当我使用 React 的 fetch API 时,我的结果以意想不到的形式返回。
fetch('http://localhost:8080/rentals')
.then((response)=> {
if (response.ok) {
return response.json();
}
throw response;
.then((jsonArr) => {
handleRentalsData(jsonArr)
})
.catch((error) => {
console.error("Error fetching data: ", error);
});
当我console.log(jsonArr)
时,浏览器报告以下内容:
Array(3) [ {...},{...},{...} ]
//Expanding this object via the console shows the following information:
---> 0: Object { id: 0, date: "2021-11-21T12:00:00Z", rentedTo: "Bob", ... }
---> 1: Object { id: 1, date: "2021-11-22T12:00:00Z", rentedTo: "Bob", ... }
---> 2: Object { id: 2, date: "2021-11-23T12:00:00Z", rentedTo: "Bob", ... }
这些索引(和浏览器的标签)表明数据现在是数组的形式,所以我就这样对待它。
我试图遍历这个数组来解析其中的 json 字符串,但是JSON.parse(data)
只产生数字(分别为 0、1 和 2),而不是像我预期的那样产生对象。
for (const json in jsonArr){
console.log(typeof json); //string
const rentalObj = JSON.parse(json);
console.log(typeof rentalObj); //number
console.log(rentalObj); //0, 1, and 2 respectively
console.log(rentalObj.date); //undefined, because rentalObj is now a number.
}
我做了一些搜索,听说数据进来的数组的索引可能会导致问题,所以我也尝试使用 reviver function 进行解析。
for (const json in jsonArr){
console.log(typeof json); //string
const rentalObj = JSON.parse(json, (key, value) => {
console.log(key); //<empty string>
console.log(value); //0, 1, and 2
return(value);
});
console.log(typeof rentalObj); //number
console.log(rentalObj); //0, 1, and 2 respectively
console.log(rentalObj.date); //undefined
}
正如预期的那样,尝试JSON.parse(jsonArr)
会引发错误。 我难住了。 为什么它会解析成一个(n 索引)数字? 当解析(或打印)数组内的字符串只产生数字时,如何提取数组内的对象?
for (const json in jsonArr) {
的json
值将设置为jsonArr
数组的“可枚举属性”,在这种情况下,它是索引。
for (const x in ['foo','bar','baz']) { console.log(x) };
// output:
// 0
// 1
// 2
所以你可能不想使用for... in
。 相反,您可以使用for... of
来迭代数组的元素:
for (const x of ['foo','bar','baz']) { console.log(x) };
// output:
// foo
// bar
// baz
注意:
for...in
不应用于迭代索引顺序很重要的数组。数组索引只是具有 integer 名称的可枚举属性,在其他方面与一般 object 属性相同。 不能保证
for...in
将按任何特定顺序返回索引。for...in
循环语句将返回所有可枚举属性,包括具有非整数名称的属性和继承的属性。因为迭代的顺序是依赖于实现的,所以对数组的迭代可能不会以一致的顺序访问元素。 因此,在访问顺序很重要的 arrays 上迭代时,最好使用带有数字索引的
for
循环(或Array.prototype.forEach()
或for...of
循环)。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.