GET with query string with Fetch in React Native

前端 未结 7 1744
情话喂你
情话喂你 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: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

提交回复
热议问题