【问题标题】:Unable to fetch data with fetch() from React Client to Nodejs Server无法使用 fetch() 从 React 客户端获取数据到 Nodejs 服务器
【发布时间】:2018-09-02 16:34:39
【问题描述】:

这是我的客户:

 handleSubmit(event) {    event.preventDefault();    alert(`starting to stream ${this.state.value} at ${this.state.volume}`)    fetch('/emitter', {
     method: 'post',
     body: JSON.stringify({
     value: this.state.value,
     volume: this.state.volume
      }),
      headers: {"Content-Type": "application/json"}
    });
    alert(`${this.state.value} and ${this.state.volume} sent to server`)    };

这是我的服务器:

app.use(express.static(__dirname + '/build'));
app.all('*', function(req, res, next) {
  res.header('Access-Control-Allow-Origin', '*');
  res.header('Access-Control-Allow-Methods', 'PUT, GET, POST, DELETE, OPTIONS');
  res.header('Access-Control-Allow-Headers', 'Content-Type');
  next();
});

app.use(bodyParser.urlencoded({
  extended: true
}));

app.post('/emitter', function (req, res) {
  console.log(req.body)
});

我只是想将数据从输入表单发送到服务器。为什么我在服务器中收到req.body 时得到一个空的{}

【问题讨论】:

    标签: node.js reactjs express


    【解决方案1】:

    编辑:

    作为参考,这是答案: https://github.com/github/fetch/issues/323#issuecomment-277510957

    app.use(bodyParser.json());
    

    需要在之后或之前添加:

     app.use(bodyParser.urlencoded({
      extended: true
    }));
    

    【讨论】:

      猜你喜欢
      • 2018-09-18
      • 2020-08-11
      • 1970-01-01
      • 2018-02-09
      • 2022-01-12
      • 2019-09-16
      • 1970-01-01
      • 2016-05-20
      • 2020-09-09
      相关资源
      最近更新 更多