从返回响应数据的Fetch Post获取数据 [英] Getting Data from Fetch Post that returns response data

查看:485
本文介绍了从返回响应数据的Fetch Post获取数据的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在带有redux的react应用程序中使用交叉获取.在我的reducer中,我使用交叉提取的post方法将一些数据保存到数据库中.保存后,我的电话将返回一个响应,其中包含一些我需要分配给状态的数据.我在解析数据时遇到了麻烦.以下是响应的样子.如何获取分配给body_init的数据?

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":

: : :

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

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

  )

} }

推荐答案

问题仅仅是我没有在返回的数据上调用.json. Doint以下解决了我的问题:

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

  )
} }

这篇关于从返回响应数据的Fetch Post获取数据的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆