简体   繁体   中英

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?

EDIT:

For reference, this is the answer: 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
}));

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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