![](/img/trans.png)
[英]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.