[SOLVED] Trouble with POST method in Fetch

I’m currently working on the voting app and I’m getting most of the components to work except one where I’m sending the identity of the user to the server via the fetch API. When the component loads I call fetch:

componentDidMount = () => {
        fetch("/user", {
            method: "post",
            body: JSON.stringify({
                user: this.context.user.username
            })
        });
    };

And on the server I handle the request, but the value of “req.body” is undefined. I tried using the bodyParser.json method to parse it but it’s not working. Can anyone help? Thanks in advance.

Hi @codefu-chivy

I noticed you have said it’s solved but haven’t elaborated so I’ll answer just in case :grin:

REStful methods need to be all caps, so you want to amend it to method: "POST".

Actually fetch works fine with lowercase methods.

What’s missing is header.

fetch('/user', {
    headers: {
      'Content-Type': 'application/json'
    },
    method: 'POST',
    body: JSON.stringify(...)
  })
1 Like

Ahh, content-type, I don’t actually think I’ve used fetch to post data, usually axios which sets the headers automatically for you. Good catch

Thanks for the replies!! Yeah I was struggling to figure out why they body was empty, but all I had to do was specify the content type in the header.

Also be aware that fetch doesn’t work on iOS, Safari and IE (http://caniuse.com/#search=fetch).
You’ll need to polyfill (I use whatwg-fetch).

I’m not quite familiar with the concept of a polyfill. So based on this documentation, all I really need to do is install and add this module in webpack, leaving everything else the way it was?

You should install whatwg-fetch, exports-loader, imports-loader and add to webpack.

const path = require('path');
const webpack = require('webpack');

module.exports = {
  entry: [
    // fetch polyfill to support iOS
    'whatwg-fetch',
    path.join(__dirname, 'src', 'index.js')
  ],

  output: {
  ...
  },

  module: {
  ...
  },

  plugins: [
    new webpack.ProvidePlugin({
      // fetch polyfill to support iOS
      'fetch': 'imports-loader?this=>global!exports-loader?global.fetch!whatwg-fetch'
    })
  ]
};

Thanks! Is there any word on when it will be officially supported by browsers like safari and IE? It seems kind of strange for such a great API to have such a gaping hole in terms of cross-browser compatibility.

IE is dead. Replaced with Edge. It will never be supported there. Don’t know about Safari. Apple has really been dragging their feet improving it.

Oh … And it’s altogether common for great APIs to not be universally supported, unfortunately.