【问题标题】:How to add progress event to react-native-fetch-polyfill如何将进度事件添加到 react-native-fetch-polyfill
【发布时间】:2018-01-22 12:48:53
【问题描述】:

我正在尝试使用react-native-fetch-polyfill,因为timeout 功能用于获取请求但无法实现onProgress 事件:

fetch('https://jsonplaceholder.typicode.com/posts', {
    method: 'POST',
    body: JSON.stringify({
      title: 'foo',
      body: 'bar',
      userId: 1
    }),
    headers: {
      "Content-type": "application/json; charset=UTF-8"
    }
  })
  .then(function(data) {
    console.log(data);
  })
  .catch(function(error) {
    console.log('Fetch Error :-S', error);
  });

我不知道在哪里添加:

onUploadProgress: function (progressEvent)

【问题讨论】:

    标签: react-native fetch


    【解决方案1】:

    该库不支持进度处理程序。如果您需要此功能并想使用该库,您最简单的做法是分叉该库并自己添加该功能:

    1) 在 GitHub 上 fork 存储库。

    2) 编辑存储库中的 js 文件。例如,添加您需要的回调作为函数的第三个参数:

    export default function fetchPolyfill (input, init) {
    // becomes
    export default function fetchPolyfill (input, init, onUploadProgress) {
    
    // add this somewhere inside
    if (onUploadProgress)
        xhr.upload.onprogress = onUploadProgress
    

    3) 编辑您的包 json 以包含
    "react-native-fetch-polyfill": "git://github.com/youraccount/react-native-fetch-polyfill"
    并运行npm install

    1a) 当然,您实际上可以只复制脚本并在您的计算机上本地编辑它,而无需处理 GitHub,如果您对它不在节点模块中感到满意的话。或者下载整个文件夹并作为一个包使用。

    【讨论】:

      【解决方案2】:

      您可以使用axios

      已经有这样的功能(onUploadProgress

      【讨论】:

        【解决方案3】:

        在底层,fetch 使用 React-Native XMLHttpRequest 对象; react-native-fetch-polyfill 也是如此。这不是浏览器中使用的常规 xhr 对象,因为实际请求是从本机端发送的。

        据我所知,RNfetchreact-native-fetch-polyfill都不支持上传进度,但是你可以直接使用XMLHttpRequest做到这一点:

        const xhr = new XMLHttpRequest();
        xhr.upload.onprogress = (progressEvent) => {
            //handle progress here, you can use progressEvent.loaded, progressEvent.total to calculate the progress
        };
        
        const body = JSON.stringify({
          title: 'foo',
          body: 'bar',
          userId: 1
        });
        xhr.setRequestHeader("Content-type", "application/json; charset=UTF-8");
        xhr.open('POST', 'https://jsonplaceholder.typicode.com/posts');
        xhr.send(body);
        

        您也可以自己添加超时处理:

        xhr.timeout = 30 * 1000;
        
        xhr.ontimeout = () => {
          //handle timeout here
        }
        

        【讨论】:

        • 我认为xhr.setRequestHeader 应该放在xhr.open 之后。运行您的示例时出现错误the quest has not been open。好的解决方案,顺便说一句
        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2019-02-26
        • 1970-01-01
        • 2022-01-15
        • 2019-10-23
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多