【问题标题】:Can I do multiple fetch in a single component in react?我可以在一个组件中进行多次获取反应吗?
【发布时间】:2018-09-22 23:47:40
【问题描述】:

我使用 react 作为前端,使用 express.js 作为后端。我对这两个框架都是新手。我有一个名为 Papers 的组件,我试图首先通过 fetch post 将一些文档上传到后端服务器,然后在服务器端执行一些操作,然后我试图在同一个处理程序中从服务器取回结果。我的处理程序代码如下所示:

        handleDrop(files) {
          var data = new FormData();

          alert((files[0]) instanceof File);
          files.forEach((file, index) => {
            data.append('file' + index, file);
          });

          fetch('/file_upload', {
            method: 'POST',
            body: data
          });

          // the second fetch would crash the app.
          /*fetch('/file_upload').then(function(data){
              return data.json();
          }).then( json => {
              this.setState({
                  papers: json
              });
              console.log(json);
          });*/
        }

我的 get 方法的快速后端代码是:

app.get('/file_upload', function(req, res){
    // testing
    res.send({name:"lol"});
});

现在的问题是第二次提取会使 express 应用程序崩溃。由于我是新来的反应和表达,如果我以正确的方式这样做,有人可以给我一些提示吗?谢谢!

服务器代码链接:https://github.com/kaiwenshi/learn-webpack/blob/master/src/server/index.js

【问题讨论】:

  • 首先,您发送 POST 请求并显示 GET 的服务器端部分。其次,您可以使用响应正文在同一个获取请求中获得答案
  • @GeorgiyDubrov 很抱歉造成混乱,post 方法有点长,所以我没有发布它。它现在在 github 链接上。

标签: javascript reactjs express


【解决方案1】:

如果您想进行 POST,Express 代码应该如下所示:

app.post('/file_upload', function(req, res){
    // testing
    res.send({name:"lol"});
});

而且您只需要调用一次 fetch。响应 ({name: 'lol'}) 将在承诺中:

    handleDrop(files) {
      var data = new FormData();

      alert((files[0]) instanceof File);
      files.forEach((file, index) => {
        data.append('file' + index, file);
      });

      fetch('/file_upload', {
        method: 'POST',
        body: data
      }).then(function(data){
          return data.json();
      }).then( json => {
          this.setState({
              papers: json
          });
          console.log(json); // logs {name: 'lol'}
      });
    }

【讨论】:

  • 您好,谢谢!所以我尝试在我的 post 方法中添加 res.send 并根据您的建议修改了我的 react fetch 代码。这次没有错误但我什么也没得到?你知道为什么会这样吗?谢谢!
  • @Rockingchief 您能否确认即使使用简单的app.post 方法(就像我提到的那样,除了发送一个简单的回复“哈哈”之外什么都不做?您发送的 Github 链接中的 app.post 非常复杂,我宁愿排除这种复杂性。
  • 所以我把那部分注释掉了,但仍然一无所获。
  • @Rockingchief 你能试着让你的获取线看起来像这样吗?我启动了一个服务器,它应该以完全相同的方式发回数据fetch('https://IncomparableGleefulSpecialist--MitchLillie.repl.co/testing', {
  • 所以我刚刚修改了我的获取代码,但仍然没有任何显示。我不确定您是否可以在发布请求中返回数据?因为我觉得这应该是获取请求的工作?再次感谢!
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-08-06
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多