Getting Data from Fetch Post that returns response data

不问归期 提交于 2019-12-11 02:59:28

问题


I am using cross fetch in a react app with redux. In my reducer I save some data to the database using cross fetch's post method. My call returns a response with some data I need to assign to state after saving. I'm having trouble parsing the data though. Below is what the response looks like. How can I get the data that is assigned to 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":

: : :

Here is the full call. My confusion is that the data returned from the api is actually already formated as json (api returns: 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))

  )

} }


回答1:


The problem was simply that I was not calling .json on my returned data. Doint the following solved my problem:

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))

  )
} }


来源:https://stackoverflow.com/questions/48738874/getting-data-from-fetch-post-that-returns-response-data

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!