2016-02-08 27 views
3

我已经尝试了一切,无法弄清楚我做错了什么。我没有问题从客户端发送数据到服务器,但反过来我无法让它工作。简单的获取请求与node.js和快递

我在客户端得到的唯一回复是ReadableByteStream {}

这是我在客户端代码:

export function getAllQuestionnairesAction(){ 
    return (dispatch, getState) => { 

    dispatch(getAllQuestionnairesRequest()); 

    return fetch(API_ENDPOINT_QUESTIONNAIRE) 
     .then(res => { 
     if (res.ok) { 
      console.log(res.body) 
      return dispatch(getAllQuestionnairesSuccess(res.body)); 
     } else { 
      throw new Error("Oops! Something went wrong"); 
     } 
     }) 
     .catch(ex => { 
     return dispatch(getAllQuestionnairesFailure()); 
     }); 
    }; 
} 

这是我在服务器上的代码:

exports.all = function(req, res) { 
    var allQuestionnaires = []; 

    Questionnaire.find({}).exec(function(err, questionnaires) { 

    if(!err) { 
     console.log(questionnaires) 
     res.setHeader('Content-Type', 'application/json'); 
     res.send(JSON.stringify({ a: 1 })); 
     //res.json(questionnaires) 
    }else { 
     console.log('Error in first query'); 
     res.status(400).send(err); 
    } 
    }); 
} 
+0

什么版本/填充工具您使用的抓取? – dvlsg

回答

2

我在这里做了一些猜测,因为我不知道是什么味道您目前使用的fetch,但我会根据fetch的标准实施进行刺探。

response里面的分辨率为fetch通常没有直接可读的.body。看到here一些直截了当的例子。

试试这个:的

export function getAllQuestionnairesAction(){ 
    return (dispatch, getState) => { 

    dispatch(getAllQuestionnairesRequest()); 

    return fetch(API_ENDPOINT_QUESTIONNAIRE) 
     .then(res => { 
     if (res.ok) { 
      return res.json(); 
     } else { 
      throw new Error("Oops! Something went wrong"); 
     } 
     }) 
     .then(json => { 
     console.log(json); // response body here 
     return dispatch(getAllQuestionnairesSuccess(json)); 
     }) 
     .catch(ex => { 
     return dispatch(getAllQuestionnairesFailure()); 
     }); 
    }; 
} 
+0

即时通讯使用https://github.com/matthew-andrews/isomorphic-fetch和https://github.com/jakearchibald/es6-promise –

+0

我认为这证实了我的怀疑 - 看他们如何有'return response.json ();'在同构提取的例子。看看我的建议是否适合你。重要的部分是'return res.json()',然后在第二个'.then()'中期待body作为承诺解析。 – dvlsg

+0

Perfekt谢谢,它的作品。 我对所有这些技术都很陌生,无法找到像这样的信息。我使用样板开始帮助,他们在那里使用这些库。你有什么来源可以阅读关于这个获取的东西吗? –