微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

javascript – Axios Promise Handling – 在react-native中获取“可能未处理的Promise Rejection – TypeError:Network request failed”

登录屏幕上的react-native应用程序中,我正在努力在输入错误用户名/密码组合后为用户提供良好的错误消息.要与API交互我正在使用Axios库.但是当我在catch语句中出现错误时,我收到这个丑陋的错误消息,说我有一个“未处理的承诺拒绝”,我不能做诸如设置组件状态或导航到新页面之类的事情.

我看不出我做错了什么,它看起来就像我在文档中看到的那样.

在我的表单提交功能中,我有

axios.post('http://192.168.1.11:1337/login',{
  email: this.state.username,password: this.state.password
}).then(function (response) {

  // This stuff all seems to work great
  console.log("The response we got: ",response);
  if (response.status == 200) {
    console.log("Status code equals 200");
    Actions.homepage();
  }
}).catch(function (err) {

  // Run into big problems when I get an error
  console.log("Got an error logging in,here's the message: ",err);
});

谁能看到我在这里做错了什么?

附:这是我从服务器返回的错误消息,它从该console.log中记录(“登录时出错,这里是消息:”,错误);:

"Got an error logging in,here's the message:"

{ [Error: Request Failed with status code 401]
  config: 
   { transformRequest: { '0': [Function: transformRequest] },transformResponse: { '0': [Function: transformResponse] },headers: 
      { Accept: 'application/json,text/plain,*/*','Content-Type': 'application/json;charset=utf-8' },timeout: 0,xsrfCookieName: 'XSRF-TOKEN',xsrfheaderName: 'X-XSRF-TOKEN',maxContentLength: -1,validateStatus: [Function: validateStatus],method: 'post',url: 'http://192.168.1.11:1337/login',data: '{"email":"zach@homies.io","password":"dddddd"}' },response: 
    { data: { message: 'Invalid password',user: false },status: 401,statusText: undefined,headers: 
     { map: 
        { connection: [ 'keep-alive' ],date: [ 'Thu,31 Aug 2017 23:30:21 GMT' ],'x-powered-by': [ 'Sails <sailsjs.org>' ],vary: [ 'X-HTTP-Method-Override' ],'content-length': [ '52' ],'access-control-allow-credentials': [ '' ],'access-control-allow-origin': [ '' ],etag: [ 'W/"34-Ymi4isRxuJ6jE1EIS+AQag"' ],'access-control-allow-methods': [ '' ],'access-control-allow-headers': [ '' ],'access-control-expose-headers': [ '' ],'content-type': [ 'application/json; charset=utf-8' ] } },config: 
       { transformRequest: { '0': [Function: transformRequest] },headers: 
         { Accept: 'application/json,request: 
        { url: 'http://192.168.1.11:1337/login',credentials: 'omit',headers: 
           { map: 
              { accept: [ 'application/json,*/*' ],'content-type': [ 'application/json;charset=utf-8' ] } },method: 'POST',mode: null,referrer: null,_bodyInit: '{"email":"zach@homies.io","password":"dddddd"}',_bodyText: '{"email":"zach@homies.io",bodyUsed: true } } }

以下是Android模拟器(仿真三星galaxy S7)的截图:

Yellow error bar showing Possible Unhandled Promise Rejection...

解决方法

这个片段没有错.

>您发送请求.
>你得到401 – 未经授权的回复.
> Catch收到错误并记录它.

有趣的部分是为什么你得到那个未处理的承诺拒绝错误.
但是这被抛到其他地方.所以你需要提供更多的代码.

编辑:也许你只需要将你的axios承诺归还给调用函数

原文地址:https://www.jb51.cc/js/157892.html

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐