Sending data as key-value pair using fetch polyfill in react-native
Question: The following code is to make HTTP POST request with fetch polyfill:

    
    
    fetch(url, {
      method: 'post',
      body: JSON.stringify({
        'token': this.state.token
      })
    })
      .then((response) => response.json())
      .then((responseData) => {
        console.log(responseData)
      })
      .done();
    

This request sends data as a stringified json obj. Is there a way to send data
as key value pair similar to requests.post(url, data=payload) in python.


Answer: Sounds like you want the same format as a querystring, so import/require a
package like <https://www.npmjs.com/package/query-string> which doesn't appear
to depend on any browser features and has a stringify method:

    
    
    queryString.stringify({
        foo: 'bar',
        nested: JSON.stringify({
            unicorn: 'cake'
        })
    });
    
    //=> foo=bar&nested=%7B%22unicorn%22%3A%22cake%22%7D 
    

Alternatively you could just use the relevant part of its source code, though
this would still be subject to [its
license](https://github.com/sindresorhus/query-string/blob/master/license):

    
    
    function toQueryString(obj) {
        return obj ? Object.keys(obj).sort().map(function (key) {
            var val = obj[key];
    
            if (Array.isArray(val)) {
                return val.sort().map(function (val2) {
                    return encodeURIComponent(key) + '=' + encodeURIComponent(val2);
                }).join('&');
            }
    
            return encodeURIComponent(key) + '=' + encodeURIComponent(val);
        }).join('&') : '';
    }
    

You can then use the return value in your `body` parameter in `fetch`:

    
    
    fetch(url, {
      method: 'post',
      body: toQueryString({ 'token': this.state.token })
    })
    

