Moss Palmer
Moss Palmer

Reputation: 1854

React Native - Interact with API - Special Characters Causing Issues - What's the best way to do this?

I cannot consistently successfully send form variables that may/may not include special characters e.g. ? & #

Depending on where I try to escape the chars I encounter different errors when reading the data server-side.

I am aware that an update is due for React Native 0.7 to include formdata but wondered if I could safely post objects without needing this.

Someone has already posted a similar issue but no example code was posted to illustrate the POST working: How to post a form using fetch in react native?

I have tried - amongst other things :

fetch(APIURL, {
  method: 'POST',
  body: JSON.stringify({
    object1: {
      param1a: "value 1a",
      param1b: "value 1b - with bad chars & # ?",
    },
    object2:
    {
      param2a: "value 2a",
      param2b: 0,
    }
  })
})

but it groups the data into a single unnamed parameter (changing the API to accept this is not an option).

also this:

fetch(APIURL, {
  method: 'GET',
  accessPackage: JSON.stringify({
      accessToken: "abc123",
      tokenType: 2,
  }),
  taggData: JSON.stringify({
    title: "test",
    wishlistID: 0,
    anotherVar: "anotherVal"
  })
})

I wish to receive the data as two strings that can be parsed as json objects at the other end.

Looking at the the fetch repo https://github.com/github/fetch hasn't helped as this assumes the post with be a full JSON post (which it isn't) or uses FormData which isn't available to React Native yet.

Another solution may be to safely encode/serialise all of the data to URL parameters but this has also proven inconsistent so far especially with the # char.

What's the best way to do this?

Upvotes: 0

Views: 2199

Answers (1)

Colin Ramsay
Colin Ramsay

Reputation: 16476

"it groups the data into a single unnamed parameter (changing the API to accept this is not an option)."

It would, because you've set the post body. This is how it's supposed to work.

I wish to receive the data as two strings that can be parsed as json objects at the other end.

You can do whatever you want, but there's no magic happening here. You will receive a single string, the string you set body to. Likewise, the post body can contain anything but shouldn't get confused with "special" characters. Most likely it is your server-side that is causing the problems.

If you want to use FormData then I think it'll be in v0.7.0 which should be out any day now, or you could probably just include the JS file in your own project. You can find it here. Usage examples are in the UIExplorer demo.

Upvotes: 1

Related Questions