用 redux fetch 反应 js 总是 return 一个空的 json

react js with redux fetch always return an empty json

我正在尝试在没有 ajax 调用的情况下请求 API(为什么我要导入整个库来简单地进行 ajax 调用?)。

所以我决定遵循 Redux 文档(我上周迁移的文档)中描述的获取函数流程。

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 是空的 object。

网络return这个:

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

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

我做错了什么吗?

您的 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)))
    };
};