【问题标题】:Getting Data from Fetch Post that returns response data从返回响应数据的 Fetch Post 获取数据
【发布时间】:2018-02-12 02:46:51
【问题描述】:

我在一个带有 redux 的反应应用程序中使用交叉提取。在我的 reducer 中,我使用 cross fetch 的 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))

  )

} }

【问题讨论】:

  • 如何将dispatch(completeTransactionsSave(res)) 更新为dispatch(completeTransactionsSave(res._bodyInit))
  • 好的。我可以试试,但是 res._bodyInit 是什么?为什么我会收到这样的回复?

标签: reactjs fetch


【解决方案1】:

问题只是我没有在返回的数据上调用 .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))

  )
} }

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2018-05-16
    • 1970-01-01
    • 2022-10-19
    • 1970-01-01
    • 2017-06-05
    • 2022-01-22
    相关资源
    最近更新 更多