jisu
jisu

Reputation: 481

Sending data as key-value pair using fetch polyfill in react-native

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.

Upvotes: 2

Views: 4289

Answers (2)

Colin Ramsay
Colin Ramsay

Reputation: 16476

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:

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 }),
});

Upvotes: 8

Jarek Potiuk
Jarek Potiuk

Reputation: 20097

Sure. Look at the fetch documentation in github: https://github.com/github/fetch

It uses document/DOM web, but it should be the same for react-native case - just use FormData object and append all the form fields to send.

var form = document.querySelector('form')

fetch('/users', {
  method: 'post',
  body: new FormData(form)
})

And:

var input = document.querySelector('input[type="file"]')

var data = new FormData()
data.append('file', input.files[0])
data.append('user', 'hubot')

fetch('/avatars', {
  method: 'post',
  body: data
})

Upvotes: 0

Related Questions