gpt4 book ai didi

响应中的 JavaScript Body.json() 丢失嵌套数组

转载 作者:行者123 更新时间:2023-11-29 23:24:03 27 4
gpt4 key购买 nike

import 'whatwg-fetch'

传入的响应如下所示(从代理中获取):

"data": {
"category_tree": [
{
"category_id": "1",
"name": "A",
"children": [
{
"category_id": 2
"name": "B, child of A",
"children": [
{
"category_id": 3,
"name": "C, child of B",
}
]
}

]
}
]
}

处理程序是这样工作的:

.then( response => response.json())

.then( json => dispatch({
type: RECEIVE_DATA,
data: json
}))

但是当 response.json() promise 解析时,数据已经丢失了所有嵌套数组:

"data": {
"category_tree": [
{
"category_id": "1",
"name": "A",
"children": []
}
]
}

有什么想法可以避免这种情况发生吗?

编辑:我得到的响应 header :

HTTP/1.1 200 OK
Server: nginx/1.10.2
Date: Thu, 12 Apr 2018 09:38:32 GMT
Content-Type: text/html; charset=UTF-8
Transfer-Encoding: chunked
Connection: keep-alive
X-Powered-By: PHP/7.1.15

Edit2:请求代码目前如下所示:

const fetchCategories = () => {
return dispatch => {
dispatch({
type: FETCH_CATEGORIES_REQUEST
})

return fetch(
`${SERVICE_API_BASE_URL}/api/categorytree?ope_flg=1`)
.then(
response => response.json(),
error => console.log("error in fetch cat", error)
)

.then(
json => console.log(json) || dispatch({
type: FETCH_CATEGORIES_RESPONSE,
categories: json
})
)
.catch(
ex => console.log("parsing failed", ex)
)
}
}

最佳答案

首先需要将响应解释为文本,然后再解析为 JSON。来自 "the body mixin for the fetch API" 上的 mozilla 文档:

Body.text() Takes a Response stream and reads it to completion. It returns a promise that resolves with a USVString (text). The response is always decoded using UTF-8.

也许 .json() 由于某些编码问题而失败?我确实尝试将 Content-Type 更改为 Content-Type: application/vnd.api+json 但这似乎没有帮助。

关于响应中的 JavaScript Body.json() 丢失嵌套数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49792947/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com