简体   繁体   中英

React + Flux, ES6, Babel ActionCreate using json-server and super agent, data not in response

Hello I am attempting to use json-server to mock up the api of an React Flux ES6 app I am building. But when I user the superagent node module to make the request from the action creator the data in the callback is undefined

Here's my code

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

My network tab says the request happens but I cannot access the response in the callback.

I figured out how to make this xhr request without superagent node module by using the fetch es2015. See here: 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));

}

Thanks!

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM