账号密码登录
微信安全登录
微信扫描二维码登录

登录后绑定QQ、微信即可实现信息互通

手机验证码登录
找回密码返回
邮箱找回 手机找回
注册账号返回
其他登录方式
分享
  • 收藏
    X
    在react-native 使用fetch发起ajax请求报错
    47
    0

    在react-native中用fetch发起请求,出现以下报错信息:
    TypeError: Network request failed

    at XMLHttpRequest.xhr.onerror (index.bundle:8369)
    at XMLHttpRequest.dispatchEvent (index.bundle:13584)
    at XMLHttpRequest.setReadyState (index.bundle:13367)
    at XMLHttpRequest.__didCompleteResponse (index.bundle:13221)
    at index.bundle:13318
    at RCTDeviceEventEmitter.emit (index.bundle:14084)
    at MessageQueue.__callFunction (index.bundle:2109)
    at index.bundle:1925
    at MessageQueue.__guard (index.bundle:2080)
    at MessageQueue.callFunctionReturnFlushedQueue (index.bundle:1924)
    

    其中:请求的代码如下:
    fetch("http://route.showapi.com/341-1").then(function(response){console.log('你好')}).catch(err => console.log(err));

    将这段请求代码,直接在chrome浏览器下运行是会输出:你好。可在RN上为什么就报错了呢?请求指教小弟

    0
    打赏
    收藏
    点击回答
        全部回答
    • 0
    • 蹲墙角才微笑 普通会员 1楼

      在React Native中,你可以使用fetch或者axios等库来发起AJAX请求。但是,如果你使用fetch发起请求并报错,可能是因为fetch的API使用了一些旧的特性,或者你没有正确配置fetch的参数。

      以下是一些常见的问题和解决方案:

      1. 使用fetch方法时,如果参数传递错误,fetch不会抛出错误,而是会返回一个错误对象。你可以通过错误对象来获取错误信息。例如:

      javascript fetch(url) .then(response => response.json()) .then(data => console.log(data)) .catch(error => console.log(error));

      1. 如果你使用axios发起请求,如果请求头的Content-Type设置错误,axios会抛出错误。你可以通过错误对象来获取错误信息。例如:

      javascript axios.get(url, { headers: { 'Content-Type': 'application/json' } }) .then(response => console.log(response.data)) .catch(error => console.log(error));

      1. 如果你的请求需要登录才能完成,你可以使用fetch的withCredentials属性来允许跨域请求。例如:

      javascript fetch(url, { withCredentials: true }) .then(response => response.json()) .then(data => console.log(data)) .catch(error => console.log(error));

      1. 如果你的请求需要身份验证,你可以使用fetch的auth模式。例如:

      javascript fetch(url, { auth: { user: 'username', pass: 'password' } }) .then(response => response.json()) .then(data => console.log(data)) .catch(error => console.log(error));

      希望这些信息对你有所帮助!

    更多回答
    网站公告
    扫一扫访问手机版
    • 回到顶部
    • 回到顶部