2016-04-27 60 views
2

我想要求一个API没有AJAX调用(为什么我会导入整个库只是做一个AJAX调用?)。反应js与REDX获取总是返回一个空JSON

因此,我决定按照Redux doc(我在上周迁移)中描述的那样执行获取函数流。

import fetch from 'isomorphic-fetch'

因此,我有这个功能的短:

export function fetchPosts(value) { 
    return dispatch => { 
     dispatch(requestPosts(value)) 
     return fetch(Config.serverUrl + '/' + value, { 
      headers: { 
       'Accept': 'application/json', 
       'Content-Type': 'application/json', 
       Authorization: Config.authorizationToken 
      }, 
     }) 
      .then(response => response.json()) 
      .then(json => dispatch(receivePosts(value, json))) 
    }; 
}; 

但是当我在做这一步功能的console.log:

function receivePosts(value, json) { 
    console.log(json); 
    return { 
     type: RECEIVE_POSTS, 
     value, 
     posts: json.data.children.map(child => child.data) 
    }; 
}; 

我可以看到我的json是一个空对象。

网络回归这样的:

General: Request URL:https://shelob-v2.dev.blippar.com/v2/categories Request Method:OPTIONS Status Code:200 OK Remote Address:52.25.79.166:443

页眉: Access-Control-Allow-Headers:Authorization, Content-Type, X-Pouet-UniqueID, X-Pouet-UniqueRunID Access-Control-Allow-Methods:PATCH, PUT, DELETE Access-Control-Allow-Origin:* Content-Length:0 Content-Type:text/plain; charset=utf-8 Date:Wed, 27 Apr 2016 14:14:36 GMT

我做得肯定是错呢?

+0

你能看看网络选项卡(chrome)中的请求/响应吗? – azium

回答

2

您的redux语法看起来正确,但它看起来像请求是OPTIONS请求而不是GET请求。尝试将method: 'GET'添加到您的提取选项。

export function fetchPosts(value) { 
    return dispatch => { 
     dispatch(requestPosts(value)) 
     return fetch(Config.serverUrl + '/' + value, { 
      method: 'GET', // here 
      headers: { 
       'Accept': 'application/json', 
       'Content-Type': 'application/json', 
       Authorization: Config.authorizationToken 
      }, 
     }) 
      .then(response => response.json()) 
      .then(json => dispatch(receivePosts(value, json))) 
    }; 
}; 
+0

的确,这次我的json已经满了! 你有什么想法,为什么我仍然有这个输出错误: '''不能读取undefined'''的属性'children'吗?是不接受receivePosts json的治疗? –

+0

听起来像这样的代码是不正确的:'json.data.children.map(child => child.data)'。我会使用网络开发工具或在您的fetchPosts或receivePosts中添加一个'console.log(json)'来确切地知道您的响应是什么样的,然后从那里开始。 – mgmcdermott