gpt4 book ai didi

reactjs - 从返回响应数据的 Fetch Post 获取数据

转载 作者:行者123 更新时间:2023-12-04 03:01:34 24 4
gpt4 key购买 nike

我在带有 redux 的 React 应用程序中使用交叉抓取。在我的 reducer 中,我使用交叉获取的 post 方法将一些数据保存到数据库中。我的调用返回一个响应,其中包含一些我需要在保存后分配给状态的数据。我在解析数据时遇到了问题。下面是响应的样子。如何获取分配给 body_init 的数据?

Response
headers
:
Headers {map: {…}}
ok
:
true
status
:
200
statusText
:
"OK"
type
:
"default"
url
:
"http://localhost:3001/api/updateTransactions"
_bodyInit
:
"[{"category":"Dining Out","months":{"1":0,"2":0,"3":0,"4":0,"5":0,"6":0,"7":0,"8":0,"9":0,"10":0,"11":0,"12":0}},{"category":"Auto","months":

:::

这是完整的调用。我的困惑是,从 api 返回的数据实际上已经格式化为 json(api 返回:res.json(items))

export function saveTransactions(transUpdate,year) {

return function (dispatch) {

dispatch(requestTransactionsSave(transUpdate))


return fetch('http://localhost:3001/api/updateTransactions',
{
method: 'post',
body: JSON.stringify(transUpdate),
headers:{'Content-Type': 'application/json'}
})
.then(
response => response,

error => console.log('An error occurred.', error)
)
.then(res =>

dispatch(completeTransactionsSave(res))

)

}

最佳答案

问题很简单,我没有对返回的数据调用 .json。请注意以下解决了我的问题:

return fetch('http://localhost:3001/api/updateTransactions',
{
method: 'post',
body: JSON.stringify(transUpdate),
headers:{'Content-Type': 'application/json'}
})
.then(
response => response.json(), //ADDED >JSON() HERE

error => console.log('An error occurred.', error)
)
.then(res =>

dispatch(completeTransactionsSave(res))

)
} }

关于reactjs - 从返回响应数据的 Fetch Post 获取数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48738874/

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