2015-07-22 35 views
3

您好,我正在嘗試使用json-server來模擬我正在構建的React Flux ES6應用程序的api。但是,當我用戶的SuperAgent節點模塊使得從行動的創建者要求在回調中的數據是不確定的React + Flux,ES6,Babel ActionCreate使用json-server和超級代理,數據沒有迴應

這裏是我的代碼

import Dispatcher from '../Dispatcher'; 
import Constants from '../Constants'; 
import request from 'superagent'; 

export default { 
    setQuestions(guides) { 
     Dispatcher.handleViewAction({ 
      type: Constants.ActionTypes.SET_QUESTIONS, 
      data: guides 
     }); 
    }, 

    getQuestionsFromServer() { 
     let self = this; 
     let destination = 'http://localhost:3000/questionnaires'; 
     // request from json service. 
     request 
     .get(destination) 
     .set({ 
       'X-Requested-With': 'XMLHttpRequest' 
      }) 
     .end(function(response) { 
      // response is empty. why??? 
      if (response.ok) { 
       let guideData; 
       guideData = response.body; 
       self.setQuestions(guideData); 
      } 
     }); 
    } 
}; 

我的網絡標籤表示該請求會發生,但我不能訪問響應在回調中。

+0

基於這個URL,我假設你正在做一個跨源請求,所以你需要設置你的模擬API來設置一個'Access-Control-Allow-Origin'頭,這樣你就可以訪問數據。如果您確認這是正確的,我會寫一個答案。 – loganfsmyth

+0

對不起,並不完全遵循你在評論中所說的話。 – loganfsmyth

回答

0

我想出瞭如何使用fetch es2015在沒有superagent節點模塊的情況下進行這個xhr請求。在這裏看到: https://developer.mozilla.org/en-US/docs/Web/API/GlobalFetch/fetch

getQuestionsFromServer() { 
    let self = this; 
    let destination = 'http://localhost:3000/questionnaires'; 
    // request from json service.response.json() 
    fetch(destination) 
     .then(response => response.json()) 
    .then(data => { 
      this.setQuestions(data[0].questions); 
     }) 
     .catch(e => console.log("Error", e)); 

}

謝謝!