K.Smith
K.Smith

Reputation: 115

Sending an array to a server to fetch some data with React Native

I am trying to do fetch a data from the server with given datas. I am using the following code :

    const details = {
      'function': 'getUsers',
    };
    const formBody = 
    Object.keys(details).map(key=>encodeURIComponent(key)+
    '='+encodeURIComponent(details[key])).join('&');
    console.log(formBody);
    fetch(url, {
      method: 'POST',
      credentials: 'include',
      headers: {
        'Accept': 'application/json',
        'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8',
        'Cookie': 'XPIDER_SID=' + this.props.text
      },
      body: formBody
      }).then((response) => response.json())
        .then((responseJson) => {
          if (responseJson.status === 'okay') {
            this.setState({ users: responseJson.users });
          } else {
             this.setState({ error: responseJson.error });
          }
      })

It works great until now. Now I have to send a array of datas but when I write an array in details constant, the server does not take the array because of the formBody. In formBody, the whole request is string, so the array converted to a string. How can I send a array with this ? or do you guys know any other option ? Thank You !

Upvotes: 3

Views: 8539

Answers (1)

linasmnew
linasmnew

Reputation: 3977

Send your array as JSON like this:

body: JSON.stringify(your_array)

Then deserialize it on the server

Upvotes: 6

Related Questions