GET with query string with Fetch in React Native

前端 未结 7 1700
情话喂你
情话喂你 2020-12-29 01:51

I am making a request like this:

fetch(\"https://api.parse.com/1/users\", {
  method: \"GET\",
  headers: headers,   
  body: body
})

How d

相关标签:
7条回答
  • 2020-12-29 02:11

    My simple function to handle this:

    /**
     * Get query string
     *
     * @param   {*}   query   query object (any object that Object.entries() can handle)
     * @returns {string}      query string
     */
    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)
    
    0 讨论(0)
  • 2020-12-29 02:14

    I did a small riff on Mark Amery's answer that will pass Airbnb's eslint definitions since many teams seem to have that requirement these days.

    function objToQueryString(obj) {
      const keyValuePairs = [];
      for (let i = 0; i < Object.keys(obj).length; i += 1) {
        keyValuePairs.push(`${encodeURIComponent(Object.keys(obj)[i])}=${encodeURIComponent(Object.values(obj)[i])}`);
      }
      return keyValuePairs.join('&');
    }
    
    0 讨论(0)
  • 2020-12-29 02:18

    Accepted answer works.. but if you have more params you're screwed. I suggest the following approach:

    let route = 'http://test.url.com/offices/search';
    if (method == 'GET' && params) {
      const query = Object.keys(params)
        .map((k) => {
          if (Array.isArray(params[k])) {
            return params[k]
              .map((val) => `${encodeURIComponent(k)}[]=${encodeURIComponent(val)}`)
              .join('&');
          }
    
          return `${encodeURIComponent(k)}=${encodeURIComponent(params[k])}`;
        })
        .join('&');
    
      route += `?${query}`;
    }
    

    EDIT: Updated answer to work with arrays as well

    0 讨论(0)
  • 2020-12-29 02:20

    Your first thought was right: just add them to the URL.

    Remember you can use template strings (backticks) to simplify putting variables into the query.

    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,   
    })
    
    0 讨论(0)
  • 2020-12-29 02:20

    Here's an es6 approach

    const getQueryString = (queries) => {
        return Object.keys(queries).reduce((result, key) => {
            return [...result, `${encodeURIComponent(key)}=${encodeURIComponent(queries[key])}`]
        }, []).join('&');
    };
    

    Here we're taking in a queries object in the shape of key: param We iterate and reduce through the keys of this object, building an array of encoded query strings. Lastly we do a join and return this attachable query string.

    0 讨论(0)
  • 2020-12-29 02:20

    Yes you should, there are a few classes in JS, that can help you a handy one is https://developer.mozilla.org/en-US/docs/Web/API/URLSearchParams

    e.g. if you had the params in a javascript object say

    let params = {one: 'one', two: 'two'}
    

    you could say this function

    let queryString = new URLSearchParams()
    for(let key in params){
      if(!params.hasOwnkey())continue
      queryString.append(key, params[key])
    }
    

    then you can get your nicely formatted query string by saying

    queryString.toString()
    
    0 讨论(0)
提交回复
热议问题