Obromios Obromios - 3 months ago 7
JSON Question

Parsing params that includes json string in rails controller

In a react-native app, I have the following post request that goes to a rails controller

fetch(POST_PAID_UP, {
method: 'POST',
body: JSON.stringify({
receipt_num: 127,
}).replace(/{|}/gi, "")
})


In the appropriate action of my rails controller I can examine params it looks like this;

{"\"receipt_num\":127"=>nil, "controller"=>"ios/accounts", "action"=>"create"}


so the data is being received. From params I need to extract the value of 'receipt_num'. I have tried
JSON.parse(params)
, but I receive this error;

TypeError: no implicit conversion of Array into String


So how should I parse this data?

Answer

You need to add headers that indicate that the information being sent is of type json. So add the following hash to the fetch instruction;

headers: {
  'Accept': 'application/json',
  'Content-Type': 'application/json',
},

You can then remove the .replace(/{|}/gi, "") which is just a work around to overcome the fact that you were not specifying the data was json. The final code should look like this:

  fetch(POST_PAID_UP, {
    method: 'POST',
    headers: {
      'Accept': 'application/json',
      'Content-Type': 'application/json',
    }, 
    body: JSON.stringify({
      receipt_num: transactionIdentifier,
      })
  })

You can find more information about fetch here