Search code examples
javascriptreact-nativefetchexpo

fetch throwing Nework request failed in React native + expo


I'm currently trying to send a request to a Flask API from my Android react native app. Thing is, fetch is always throwing the same error, Network request failed. I've been looking around, but none of the answers I've found apply. I've made sure the request is headed to the right address and port, and it looks all good. I've tried making the same request using Postman and it works fine, so I know the server is working.

Here's my code:

function apiRequest(path, method, body = "") {
  const url = path;

  console.log("going");
  console.log(url);
  fetch(url, {
    method: method,
    headers: {
      "Cache-control": "no-cache",
    },
    body: body,
  })
    .then((response) => {
      if (response.ok) {
        if (response.status == 204) {
          return true;
        }
        return response.json();
      }
      throw new Error(`${response.status}: ${response.body}`);
    })
    .then((json) => {
      console.log(json);
      return json;
    })
    .catch((error) => {
      console.log("ERRORED:");
      console.error(error);
    });
}
var response = apiRequest(
  "http://192.168.2.244:5000/driver/register",
  "POST",
  JSON.stringify({
    name: name,
    email: email,
    password: password,
  })
);
console.log(`RES: ${response}`);

Any help would be greatly appreciated.


Solution

  • You should try adding 'Content-Type' in headers:

    headers: {
        Accept: 'application/json',
        'Content-Type': 'application/json'  // I added this line
    }