I am developing an application with React Native, which communicates with an IoT chip (with very little ram memory), because of that all the logic must be developed on the client side.
One of the specifications of this chip is all the characters “,” must to be escaped with just one trilling slash.
Ex:
From:
{ value: 'foo,bar' }
To:
{ value: 'foo,bar' }
I am sending this information using axios:
import axios from 'axios'; const body = { value: 'foo,bar' }; const parsedBody = { value: body.value.replace(/,/g, '\,') } // { value: 'foo,bar' } axios({ method: 'POST', headers: { Accept: 'application/json', 'Content-Type': 'application/json; charset=utf-8', }, url: 'https://example.com', data: body, }).then(response => { console.log('message sent!'); });
The problem is that on the other side, the server is receiving the body (as an object) with an extra trilling slash
Ex:
{ value: 'foo\,bar' }
I’m not sure if the information is being modified by axios. But I need to receive it with only one trilling slash (I can’t parse it on the server side)
Advertisement
Answer
Since you are passing an object as data
, I strongly assume that axios uses JSON.stringify()
to convert that object into a string. The correct JSON representation of the object { value: 'foo\,bar' }
is {"value":"foo\,bar"}
, so with the double quotes and the double backslash.
Now I’m not familiar with axios and its documentation doesn’t seem to be very detailed, but maybe try passing a string as data
. Then you have full control over the way it is encoded.
A very simple way to try this would be data: JSON.stringify(parsedBody).replace(/\\,/g, '\,')
.
This will obviously not work if you ever intentionally want to send \,
instead of ,
. So depending on what kind of data you are planning to send, you might need to implement your own stringification function (for example: data: `{ value: '${body.value.replace(/([',\])/g, '\$1')}' }`
)