Daniel Storch February 2016

Simple get request with node.js and express

I have tried everything and can't figure out what i am doing wrong. I have no problem posting data from the client to the server but the other way around i can't get it to work.

The only response i get in my client is ReadableByteStream {}.

This is my code on the client:

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

This is my code on the server:

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

Answers


dvlsg February 2016

I'm doing some guesswork here, since I'm not sure what flavor of fetch you are currently using, but I'll take a stab at it based on the standard implementation of fetch.

The response inside the resolution of fetch typically does not have a directly readable .body. See here for some straight forward examples.

Try this:

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

Post Status

Asked in February 2016
Viewed 2,137 times
Voted 5
Answered 1 times

Search




Leave an answer