[SOLVED] Trouble with POST method in Fetch

[SOLVED] Trouble with POST method in Fetch
0

#1

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.


#2

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".


#3

Actually fetch works fine with lowercase methods.

What’s missing is header.

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

#4

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


#5

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.


#6

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).


#7

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?


#8

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'
    })
  ]
};

#9

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.


#10

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.


#11

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