2016-03-13 27 views
2

我們正在構建一個反應程序(沒有終極版,但使用的WebPack)使用愛可信做一個GET請求到服務器,服務器接收到請求(即,我們看到我們的控制檯。日誌語句),但請求的響應從未提供,因爲我們從我們的console.log得到任何數據傳回擱置..服務器似乎無所事事我們到Response.End/response.send語句。執行難度在REACTjs GET請求,而終極版

有沒有人處理這件事?任何人有任何提示?請參閱下面的代碼。

//Within our react component file 

componentWillMount(){ 

     console.log("inside of componentWillMount!"); 

     return axios.get('/api/test') 
     .then(function(resp){ 
     return resp.data; 
     console.log('axios response: ', resp); 
     }) 
     .catch(function(resp) { 
     console.log('axios catch response ', resp); 
     }); 
    } 




//From our server.js file 


    // additional middleware to set headers that we need on each request 
    app.use(function(req, res, next) { 

     // disable caching so we'll always get the latest activities 
     res.setHeader('Cache-Control', 'no-cache'); 
     next(); 
    }); 

    app.get('/api/test', function(request, response, err) { 
     //mongoose find all here 
     console.log("We're in the server!!!"); 

     response.end("ennnndddd"); 

     if(err){ 
     console.log("ERROR!", err); 
     } 
    }); 




    app.listen(port, function() { 
    console.log('Proxy listening on port 3000!'); 
    }); 

回答

0

你爲什麼從componentWillMount返回你的調用?我不認爲你應該從那個反應生命週期事件中退回你的axios調用。我不認爲它會被稱爲。

在現實中你的數據呼叫不應該在你的組件在所有。你應該在你行動的創建者數據呼叫然後將其派遣到你的減速。

例如:

 
    // Action Creator 
    import axios from 'axios' 
    export const TEST = 'TEST' 

    export function testApi (city) { 
     return (dispatch) => { 
     axios.get('/api/test').then(
      (resp) => { 
      dispatch({ 
       type: TEST, 
       payload: resp.data // or something like that 
      }) 
      }, 
      (err) => { 
      console.error(err) 
      } 
     ) 
     } 
    } 


    // Reducer 
    import { TEST } from 'actions/index' 

    export default function (state = {}, action) { 
     switch (action.type) { 
     case TEST: 
      return Object.assign({}, state, action.payload) 
     } 

     return state 
    } 


    // Component 
    componentWillMount() { 
     this.props.dispatch(testApi()) 
    }