【问题标题】:Network request failed when trying POST request in React-Native在 React-Native 中尝试 POST 请求时网络请求失败
【发布时间】:2020-03-28 04:45:23
【问题描述】:

我正在尝试从我的 React 本机应用程序向本地服务器 POST 请求,但出现错误。

我构建了一个通用的httpMethod函数

export async function httpMethod(req) {
  try {
    var response = fetch(`${apiUrl}${req.api}`, {
      method: req.method,
      headers: req.headers
        ? req.headers
        : {
            'Content-Type': 'application/json'
          },
      body: JSON.stringify(req.body)
    });
    return response;
  } catch (error) {
    console.error(error);
  }
}

我从这个方法中调用它:

export async function registerUser(props) {
  try {
    const { email, password } = props;
    let api = `/users`;
    return await httpMethod({
      method: 'POST',
      api,
      body: { email, password }
    });
  } catch (error) {
    console.error(error);
  }
}

网址是http://0.0.0.0:9000/users

当尝试通过邮递员发布此内容时,一切正常:

添加一些控制台日志以确保我的 HTTP 请求 URL 和参数正常后,我收到此错误:

HTTP POST  request to -- http://0.0.0.0:9000/users
 req.body: {"email":"Test@gmail.mmm","password":"@Aa123456"}    
 headers: undefined

Network request failed
- node_modules\react-native\Libraries\vendor\core\whatwg-fetch.js:504:15 in XMLHttpRequest.xhr.onerror
- node_modules\event-target-shim\lib\event-target.js:172:38 in XMLHttpRequest.dispatchEvent
- ... 9 more stack frames from framework internals

我做错了什么?

【问题讨论】:

  • 我认为您需要定义您的请求标头,看起来您在代码中将标头定义为至少 content-type: application/json,但它们在您的控制台中显示为 undefined日志。
  • 尝试使用你的IP地址IP_ADDRESS:9000/users而不是0.0.0.0:9000/users

标签: javascript react-native http fetch


【解决方案1】:

嗯,答案让我很尴尬:

在我的实际手机上运行应用程序时,地址“http://0.0.0.0:9000/users

指的不是服务器地址,而是手机地址。

从 android 模拟器运行请求时,它运行良好,

当对我的实时服务器地址运行相同的请求时,它运行良好。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2019-01-06
    • 1970-01-01
    • 2021-04-07
    • 2020-07-23
    • 2020-04-27
    • 2019-08-11
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多