Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

isomorphic fetch post can't read body on server

I'm struggling with this strange problem, I can't seem to solve. I'm using isomorphic fetch to to post data to a server. I'm sending the body as a JSON-string. But on the server, I can't read the body, it's just an empty object.

The stack is: node, react.

Here is the client-code:

handleSubmit = (event) => {
    const { dispatch } = this.props;

    fetch('/api/me', {
      method: 'POST',
      header: {
        'Accept': 'application/json',
        'Content-Type': 'application/json'
      },
      body: JSON.stringify({
        name: 'xxx'
      })
    })
    .then(response => response.json())
    .then( json => dispatch( login( json ) ))
    .catch( err => console.log(err) )
  }

The server code:

var jsonParser = bodyParser.json()
app.post( '/api/me', jsonParser, ( req, res ) => {
  console.log('req', req.body);
})

I've tried googling the problem. But the few solutions I found, didn't to the trick.

All help is much appreciated.

BR

Martin

// UPDATE //

figured it out, it was a silly 's', I had forgotten. 'header' should be 'headers'

like image 728
Martin Kure Avatar asked Dec 05 '15 10:12

Martin Kure


1 Answers

Thank you for the update that one of the params should be plural:

  headers: {
    'Accept': ...,
    'Content-Type': ...
  },

You appended it to the question. Please feel free to accept this as the answer, or to create a new answer with that text, and accept it. Then the "unanswered" queue will contain one less dangling entry for folks to stumble upon.

like image 183
J_H Avatar answered Oct 18 '22 20:10

J_H