简体   繁体   English

无法使用 fetch() 从 React Client 到 Nodejs Server 获取数据

[英]Unable to fetch data with fetch() from React Client to Nodejs Server

So this is my client:所以这是我的客户:

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

and this is my 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)
});

I'm simply trying to send data from an input form to a server.我只是想将数据从输入表单发送到服务器。 Why am I getting an empty {} when I received the req.body in the server?当我在服务器中收到req.body时,为什么我得到一个空的{}

EDIT:编辑:

For reference, this is the answer: https://github.com/github/fetch/issues/323#issuecomment-277510957作为参考,这是答案: https : //github.com/github/fetch/issues/323#issuecomment-277510957

app.use(bodyParser.json());

needs to added after or before:需要在之后或之前添加:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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