反应本机获取http请求抛出错误 [英] react native fetch http request throw error

查看:47
本文介绍了反应本机获取http请求抛出错误的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试在React Native应用中发出http请求,这使我抛出错误

 未捕获错误:不支持的BodyInit类型在Response.Body._initBody(index.bundle?platform = android& dev = true& minify = false:13594)在新的响应时(index.bundle?platform = android& dev = true& minify = false:13765)在XMLHttpRequest.xhr.onload(index.bundle?platform = android& dev = true& minify = false:13820) 

在我添加此行的应用程序的index.js中

  GLOBAL.XMLHttpRequest = GLOBAL.originalXMLHttpRequest ||GLOBAL.XMLHttpRequest 

获取请求

  const headers = {};headers ['Accept'] ='application/json';headers ['Content-Type'] ='application/json';let response = await fetch('https://www.saramashkim.co.il/api/get_all_product',{方法:"GET",标头:标头,正文:null,}) 

当我在POSTMAN中检查此URL时,它工作正常,并且我获取了所有数据.

解决方案

尝试以下代码:

  var headers = {'Accept':'application/json','Content-Type':'application/json'};fetch('https://www.saramashkim.co.il/api/get_all_product',{方法:"GET",标头:标头,}).then(((response)=> response.json()).then((responseJson)=> {console.log('response',responseJson);}).catch((错误)=> {console.error(错误);}); 

您可以看到响应已记录到控制台.(我已经更新了答案)

repl:

I'm trying to make http request in react native app and it throws me an error

Uncaught Error: unsupported BodyInit type
at Response.Body._initBody (index.bundle?platform=android&dev=true&minify=false:13594)
at new Response (index.bundle?platform=android&dev=true&minify=false:13765)
at XMLHttpRequest.xhr.onload (index.bundle?platform=android&dev=true&minify=false:13820)

in index.js of the app I added this line

GLOBAL.XMLHttpRequest = GLOBAL.originalXMLHttpRequest || GLOBAL.XMLHttpRequest

fetch request

            const headers = {};
        headers['Accept'] = 'application/json';
        headers['Content-Type'] = 'application/json';
        let response = await fetch('https://www.saramashkim.co.il/api/get_all_product', {
            method: 'GET',
            headers: headers,
            body:  null,
        })

when I check this url in POSTMAN it works fine and I get all data..

解决方案

Try the code below:

var headers = {'Accept': 'application/json', 'Content-Type': 'application/json'};
fetch('https://www.saramashkim.co.il/api/get_all_product', {
    method: 'GET',
    headers: headers,
}).then((response) => response.json())
  .then((responseJson) => {
    console.log('response', responseJson);
  })
  .catch((error) =>{
    console.error(error);
  });

You can see the response is logged to console. (I've updated my answer)

repl: https://repl.it/@tejashwikalptar/samplefetchtest

Screenshot:

这篇关于反应本机获取http请求抛出错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆