user938363
user938363

Reputation: 10350

Pass a params like it is in body of POST

fetch can be used like this in react native:

fetch(`https://api.parse.com/1/users?foo=${encodeURIComponent(data.foo)}&bar=${encodeURIComponent(data.bar)}`, {
  method: "GET",
  headers: headers,   
})

The params key/value pair is passed in with URL. Is there a way I can pass a params (for GET) like a body in POST, without revealing to outside?

Upvotes: 0

Views: 68

Answers (1)

Diksha235
Diksha235

Reputation: 452

You can do this through this way

const data = {foo:1, bar:2};

fetch(`https://api.parse.com/1/users?foo=${encodeURIComponent(data.foo)}&bar=${encodeURIComponent(data.bar)}`, {
  method: "GET",
  headers: headers,   
})

Alternative :

let params = {
  "param1": "value1",
  "param2": "value2"
}

let query = Object.keys(params)
             .map(k => encodeURIComponent(k) + '=' + encodeURIComponent(params[k]))
             .join('&');

let url = 'https://api.parse.com/1/users?' + query 

fetch(url)
  .then(data => data.text())
  .then((text) => {
    console.log('request succeeded with JSON response', text)
  }).catch(function (error) {
    console.log('request failed', error)
  })

You can hide the values from URL through this. It will encode the key and values. Hope it helps.

    function querystring(query = {}) {
  // get array of key value pairs ([[k1, v1], [k2, v2]])
  const qs = Object.entries(query)
    // filter pairs with undefined value
    .filter(pair => pair[1] !== undefined)
    // encode keys and values, remove the value if it is null, but leave the key
    .map(pair => pair.filter(i => i !== null).map(encodeURIComponent).join('='))
    .join('&');

  return qs && '?' + qs;
}

querystring({one: '#@$code', two: undefined, three: null, four: 100, 'fi##@ve': 'text'});
// "?one=%23%40%24code&three&four=100&fi%23%23%40ve=text"
querystring({});
// ""
querystring('one')
// "?0=o&1=n&2=e"
querystring(['one', 2, null, undefined]);
// "?0=one&1=2&2" (edited)

Upvotes: 2

Related Questions