从返回响应数据的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))
)
} }