未处理的承诺拒绝:错误:网络错误

时间:2020-03-11 07:32:50

标签: javascript api react-native axios backend

我正在尝试从API获取数据。

我这样做了:

const testScreen=()=>{

const c =  axios.get("http://localhost:3000/unverifiedProperty/warehouse",{
    headers:{
        'Authorization':'Bearer eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJlbWFpbCI6InN1dGhhcmhpbWFzbmh1OThAZ21haWwuY29tIiwiaWF0IjoxNTgzODY0NjgwfQ.fxclNhIaNkTnINwOinqFRitX_AA7nQCrLtaFBLY99Tc'
    }
})
console.log(c)

return(
    <View>
        <Text>This is test Screen</Text>

    </View>
)}

我想使用获取请求获取数据。

在终端中,我得到了:

  Running application on Himanshu.
  Promise {
  "_40": 0,
  "_55": null,
  "_65": 0,
  "_72": null,
  }

[Unhandled promise rejection: Error: Network Error]
- node_modules\axios\lib\core\createError.js:15:17 in createError
- node_modules\axios\lib\adapters\xhr.js:78:22 in handleError
- node_modules\event-target-shim\dist\event-target-shim.js:818:39 in EventTarget.prototype.dispatchEvent
- node_modules\react-native\Libraries\Network\XMLHttpRequest.js:574:29 in setReadyState
- node_modules\react-native\Libraries\Network\XMLHttpRequest.js:388:25 in __didCompleteResponse
- node_modules\react-native\Libraries\vendor\emitter\EventEmitter.js:190:12 in emit
- node_modules\react-native\Libraries\BatchedBridge\MessageQueue.js:436:47 in __callFunction
- node_modules\react-native\Libraries\BatchedBridge\MessageQueue.js:111:26 in __guard$argument_0
- node_modules\react-native\Libraries\BatchedBridge\MessageQueue.js:384:10 in __guard
- node_modules\react-native\Libraries\BatchedBridge\MessageQueue.js:110:17 in __guard$argument_0
* [native code]:null in callFunctionReturnFlushedQueue

我已确保使用邮递员没有网络问题。您可以在以下屏幕截图中查看: enter image description here

请在这里帮助我。

3 个答案:

答案 0 :(得分:0)

首先缺少功能测试筛孔右括号(})

其次axios.get(或任何其他方法)返回promise。 要访问您的c,您需要执行类似操作。 如果诺言失败,它将被缓存在.catch方法中,您可以将其记录下来,看看是否有问题

const c =  axios.get("http://localhost:3000/unverifiedProperty/warehouse",{
    headers:{
        'Authorization':'Bearer 0000000'
    }
}).then(res=>res)
.catch(err=>err)

以下是承诺如何运作的链接https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise

答案 1 :(得分:0)

这是示例axios.get,用于从服务器获取数据

const c = axios
  .get("http://localhost:3000/unverifiedProperty/warehouse", {
    headers: {
       Authorization: "Bearer eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJlbWFpbCI6InN1dGhhcmhpbWFzbmh1OThAZ21haWwuY29tIiwiaWF0IjoxNTgzODY0NjgwfQ.fxclNhIaNkTnINwOinqFRitX_AA7nQCrLtaFBLY99Tc"
    }
  })
  .then(res => res) //Response from the server
  .catch(err => err); 

如果您在Android模拟器上进行测试,我认为您的问题是 localhost

尝试使用此IP地址 10.0.2.2

代替 localhost

赞:

http://10.0.2.2:3000/unverifiedProperty/warehouse

答案 2 :(得分:0)

有时,如果我们使用Localhost,通常会在您遇到错误时发生错误,请尝试使用计算机的IP地址。

如果您是Linux或Mac用户,则可以通过 ifconfig

进行检查

如果您是Windows用户,则可以使用以下命令:cmd中的 ipconfig

然后用您的IP地址替换localhost。