0
votes

I have a function that makes a request using the fetch function and I'm not able to get the result on android, but with the same code i can get on website...

the function :

async submit() {
    var data = new FormData();
    data.append('nome', this.state.nome);
    data.append('endereco', this.state.endereco);
    data.append('foto', this.state.foto.uri);
    
    const resposta = await fetch("webapiexample.com/create.php", {
        method: 'POST',
        body: data,
    }).then((e) => e.json())
    .catch(function (error) {
        console.log("miss");
        console.log(error);
      });
    console.log(resposta)
}

on website i got this result:

{msg: "Inserido com sucesso!", erro: false}

and on real android device i got this (the undefined is the same console.log before):

miss

undefined

JSON Parse error: Unrecognized token '<' [native code]:null in parse

  • node_modules\react-native\node_modules\promise\setimmediate\core.js:37:13 in tryCallOne
  • node_modules\react-native\node_modules\promise\setimmediate\core.js:123:24 in setImmediate$argument_0
  • node_modules\react-native\Libraries\Core\Timers\JSTimers.js:130:14 in _callTimer
  • node_modules\react-native\Libraries\Core\Timers\JSTimers.js:181:14 in _callImmediatesPass
  • node_modules\react-native\Libraries\Core\Timers\JSTimers.js:441:30 in callImmediates
  • node_modules\react-native\Libraries\BatchedBridge\MessageQueue.js:387:6 in __callImmediates
  • node_modules\react-native\Libraries\BatchedBridge\MessageQueue.js:135:6 in __guard$argument_0
  • node_modules\react-native\Libraries\BatchedBridge\MessageQueue.js:364:10 in __guard
  • node_modules\react-native\Libraries\BatchedBridge\MessageQueue.js:134:4 in flushedQueue
  • [native code]:null in flushedQueue
  • [native code]:null in invokeCallbackAndReturnFlushedQueue
1

1 Answers

0
votes

The error is happening on this line: e.json(), data returned by the server is not valid JSON. You can log the data by doing:

const resposta = await fetch("webapiexample.com/create.php", {
  method: 'POST',
  body: data,
}).then((e) => {
  return e.text();
}).then((text) => {
  console.log('raw text:', text);
  return JSON.parse(text);
}).catch(function (error) {
  console.log("miss");
  console.log(error);
});

Generally this code does not look nice, please avoid mixing promise syntax with async/await.