0

Trying to debug a new React-native application -- pretty large and it has no backend so I am trying to stub something out.

The request format is pretty foreign to me. Does anyone recognize this format or know how to handle it?

proc_name=customer_ref&params={"fields" : ["customerId"],"conditions":[{"mailAddress":"dsadsa"},{"pinCode":"ZHNhZHNh"},{"mailReceiveFlag":"1"}],"order" : ["customerCode desc"],"limit" : "1","table_name" : "Customer"}

React-native request code looks like this:

try{
    let result = await fetch(apiUrl, {
        method: 'POST',
        headers: {
          'X_contract_id': contact_id,
          'X_access_token': access_token,
          'Content-Type': 'application/x-www-form-urlencoded',
          'charset':'UTF-8',
        },
        body: 'proc_name='+proc_name+'&params={'+params+'}'
    }).then((response) => response.json())
    .then((responseJson) => {
      return responseJson.result;
    })
    return result;
}catch(e){
    console.log(e);
}

The application errors out with Unhandled Promise Rejection before even making it to the server I whipped up. Pretty new here; am I doing something wrong at the frontend layer?

Daniel Thompson
  • 2,193
  • 4
  • 23
  • 37
  • 1
    The params look more like a JSON string. If the Content type was application/json, I will recommend JSON.stringify(params). – vijayst Feb 09 '18 at 03:27

1 Answers1

0

Try changing your fetch structure to be like this.

async functionName(){

try{
    let result = await fetch(apiUrl, {
        method: 'POST',
        headers: {
          'X_contract_id': contact_id,
          'X_access_token': access_token,
          'Content-Type': 'application/x-www-form-urlencoded',
          'charset':'UTF-8',
        },
        body: 'proc_name='+proc_name+'&params={'+params+'}'
    });
    let resultjson = await result.json();
    return resultjson.result;
}catch(e){
    console.log(e);
}

}

https://facebook.github.io/react-native/docs/network.html

DennisFrea
  • 1,112
  • 8
  • 10
  • Because the fetch is asynchronous so you cannot use try-catch statements to handle exceptions thrown asynchronously. Take a look here if you need another info https://stackoverflow.com/questions/24977516/catching-errors-in-javascript-promises-with-a-first-level-try-catch – DennisFrea Feb 09 '18 at 03:40
  • I see the same error either way, whether it's caught in the overarching try statement, or attached to the promise through the catch handler – Daniel Thompson Feb 09 '18 at 03:42
  • 1
    Btw, is this code being put inside async function or not? Eg: async testfunction(){...} – DennisFrea Feb 09 '18 at 03:51
  • ahh yeah sorry left that out DX – Daniel Thompson Feb 09 '18 at 03:58
  • Also try to change your code based on the docs, I just updated the answer – DennisFrea Feb 09 '18 at 04:13