在 React native + expo 中获取抛出网络请求失败

fetch throwing Nework request failed in React native + expo

我目前正在尝试从我的 Android React 本机应用向 Flask API 发送请求。问题是,fetch 总是抛出相同的错误,Network request failed。我一直在四处寻找,但我找到的答案中 none 是适用的。我已确保请求发送到正确的地址和端口,并且看起来一切正常。我已经尝试使用 Postman 发出相同的请求并且它工作正常,所以我知道服务器正在工作。

这是我的代码:

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}`);

如有任何帮助,我们将不胜感激。

您应该尝试在 headers 中添加 'Content-Type':

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