2016-02-08 25 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謝謝,它的作品。 我對所有這些技術都很陌生,無法找到像這樣的信息。我使用樣板開始幫助,他們在那裏使用這些庫。你有什麼來源可以閱讀關於這個獲取的東西嗎? –