使用Node.js和Express进行简单的GET请求

3

我已经尝试了一切,但无法弄清楚我做错了什么。我在客户端向服务器发送数据没有问题,但反过来就无法让它正常工作。

我在客户端只收到一个响应: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);
    }
  });
}

你使用的是哪个版本/ polyfill 的 fetch? - dvlsg
1个回答

2
我正在猜测,因为我不确定你当前使用的是哪种fetch版本,但我将根据标准实现的fetch进行尝试。

fetch解析中的response通常没有可直接读取的.body。可以查看这里获取一些简单明了的示例。

尝试这个:

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

我正在使用 https://github.com/matthew-andrews/isomorphic-fetch 和 https://github.com/jakearchibald/es6-promise。 - Daniel Storch
我认为这证实了我的怀疑——看看isomorphic-fetch的示例中他们如何使用return response.json();。看看我的建议是否适用于你。重要的部分是return res.json(),然后在第二个.then()中将body作为promise解析。 - dvlsg
非常感谢,它有效了。 我对所有这些技术都很陌生,很难找到关于这种东西的信息。我正在使用一个起始帮助的样板,在那里他们使用了这些库。你有任何可以阅读关于这个fetch的资料来源吗? - Daniel Storch
2
@DanielStorch https://developer.mozilla.org/zh-CN/docs/Web/API/Fetch_API/Using_Fetch 是一个很好的起点。 - sideshowbarker

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接