【问题标题】:React Native returns [Unhandled promise rejection: TypeError: Network request failed] when I'm making a Post Request当我发出发布请求时,React Native 返回 [未处理的承诺拒绝:TypeError:网络请求失败]
【发布时间】:2020-06-30 00:16:18
【问题描述】:

当我使用 Axios 在 React Native 中发出 post 请求时,它会返回 [Unhandled Promise Rejection: TypeError: Network request failed]。 这是我的 json 和我的 axios 方法

const credentials= {
NickName: "ricardo.luna",
Password: "123",
AccesoAplicacion: 1,
DerechosRangoInicial: 1000,
DerechosRangoFinal: 1012
}

const loginAxios = () => {
axios
  .post('x.x.x.x/API/users', credentials)
  .then(response => {
    console.log(response.IdUser);
  });
 };

【问题讨论】:

    标签: javascript react-native post axios http-post


    【解决方案1】:

    您需要将您的帖子参数传递为FormData

    let bodyFormData = new FormData();
    
    bodyFormData.set('NickName', 'Fred');
    bodyFormData.set('Password', '123');
    bodyFormData.set('AccesoAplicacion', 1);
    bodyFormData.set('DerechosRangoInicial', 1000);
    bodyFormData.set('DerechosRangoFinal', 1012);
    
    const loginAxios = () => {
    axios({
        method: 'post',
        url: 'x.x.x.x/API/users',
        data: bodyFormData,
        headers: {'Content-Type': 'multipart/form-data' }
        })
        .then(function (response) {
            //handle success
            console.log(response);
        })
        .catch(function (response) {
            //handle error
            console.log(response);
        });
    };
    

    或者您可以使用querystring 模块来构建您的查询字符串

    const querystring = require('querystring');
    
    const credentials= {
    NickName: "ricardo.luna",
    Password: "123",
    AccesoAplicacion: 1,
    DerechosRangoInicial: 1000,
    DerechosRangoFinal: 1012
    }
    
    const loginAxios = () => {
    axios
      .post('x.x.x.x/API/users', querystring.stringify(credentials))
      .then(response => {
        console.log(response.IdUser);
      });
     };
    

    【讨论】:

    • 谢谢,我使用了第一个结构,但没有使用 FormData,而是使用了我的凭据对象并顺利运行
    • @RicardoLuna 很高兴为您提供帮助,也请不要忘记投票?
    • 谢谢,但它显示“感谢您的反馈!声望低于 15 人的投票将被记录,但不要更改公开显示的帖子得分。” :( 这实际上是这里要做的第一个问题
    【解决方案2】:

    只需在 .then() 之后添加 .catch(error=>{}) 即可处理拒绝并捕获返回的错误

    【讨论】:

      猜你喜欢
      • 2021-06-25
      • 1970-01-01
      • 2020-10-28
      • 1970-01-01
      • 2020-07-12
      • 1970-01-01
      • 2021-04-12
      • 2018-06-27
      • 2021-05-28
      相关资源
      最近更新 更多