【问题标题】:Got undefined from the CORS API call in React从 React 中的 CORS API 调用未定义
【发布时间】:2017-12-14 18:01:36
【问题描述】:

我正在尝试使用 CORS 调用本地托管的 REST API,并获取数据以在使用 React 编写的前端进行可视化。但是我不断从数据获取函数中得到未定义,当我在“onload”处理程序中控制台输出数据时,该函数运行良好。这是我的两个数据获取脚本:

// App.js
import {fetchIntradayDataHR, fetchDailyLogHR} from './DataFetch';

// ...
  componentWillMount() {
    // Called the first time when the component is loaded right before the component is added to the page
    this.getChartData();
  }
  
  getChartData() {
    var url = "http://127.0.0.1:8080/heart";
    // var response = fetchIntradayDataHR(url);


    console.log(fetchIntradayDataHR(url));
    *// Got undefined here.*


    this.setState({ ... });
  }
  
  
// DataFetch.js
// Helper function to sort out the Browser difference
function createCORSRequest(method, url) {
  var xhr = new XMLHttpRequest();
  if ("withCredentials" in xhr) {
    // "withCredentials" only exists on XMLHTTPRequest2 objects.
    xhr.open(method, url, true);
  } else if (typeof XDomainRequest != "undefined") {
    // Otherwise, check if XDomainRequest.
    xhr = new XDomainRequest();
    xhr.open(method, url);
  } else {
    // Otherwise, CORS is not supported by the browser.
    xhr = null;
  }
  return xhr;
}

export function fetchIntradayDataHR(url) {
  var xhr = createCORSRequest('GET', url);
  if(!xhr) {
    alert('CORS not supported!');
    return {};
  }

  xhr.onload = function() {
    var parsedResponse = JSON.parse(xhr.responseText);
    var parsedObj = renderIntradayData(parsedResponse);


    console.log(parsedObj);
    // Got the correct result here tho...


    return parsedObj;
  };

  xhr.onerror = function() {
    alert('Error making the request!');
    return {};
  };

  xhr.send();
}

// ...

【问题讨论】:

    标签: javascript reactjs cors frontend backend


    【解决方案1】:

    fetchIntradayDataHR 是一个异步函数。然后,您需要传递一个回调以在响应到来时运行。

    所以,第一个变化是 fetch 函数的签名:

    export function fetchIntradayDataHR(url, onSuccess, onLoad) {}
    

    而不是

    export function fetchIntradayDataHR(url) {}
    

    然后在 React 组件中,您将相应地调用此函数,回调将包含this.setState

    var url = "http://127.0.0.1:8080/heart";
    
    const onSuccess = (response) => this.setState({ok : true}); 
    const onError = (error, response) => this.setState({ok: false}); 
    fetchIntradayDataHR(url, onSuccess, onError);
    

    而不是

    var url = "http://127.0.0.1:8080/heart";
    // var response = fetchIntradayDataHR(url);
    
    
    console.log(fetchIntradayDataHR(url));
    
    this.setState({ ... });
    

    简单的代码可以如下:

    // App.js
    import {
      fetchIntradayDataHR,
      fetchDailyLogHR
    } from './DataFetch';
    
    // ...
    componentWillMount() {
      // Called the first time when the component is loaded right before the component is added to the page
      this.getChartData();
    }
    
    getChartData() {
      const url = "http://127.0.0.1:8080/heart";
      // var response = fetchIntradayDataHR(url);
      const onSuccess = (data) => this.setState({data: data, fetching: false});  //!--- ⚠️ ATTENTION
      const onError = (error) => this.setState({message: error, fetching: false});  //!--- ⚠️ ATTENTION
      this.setState({fetching: true}); // start fetching
      fetchIntradayDataHR(url, onSuccess, onError);  //!--- ⚠️ ATTENTION
      console.log(fetchIntradayDataHR(url)); * // Got undefined here.*
    
    
      this.setState({...
      });
    }
    
    
    // DataFetch.js
    // Helper function to sort out the Browser difference
    function createCORSRequest(method, url) {
      var xhr = new XMLHttpRequest();
      if ("withCredentials" in xhr) {
        // "withCredentials" only exists on XMLHTTPRequest2 objects.
        xhr.open(method, url, true);
      } else if (typeof XDomainRequest != "undefined") {
        // Otherwise, check if XDomainRequest.
        xhr = new XDomainRequest();
        xhr.open(method, url);
      } else {
        // Otherwise, CORS is not supported by the browser.
        xhr = null;
      }
      return xhr;
    }
    
    export function fetchIntradayDataHR(url, onSuccess, onError) {
      var xhr = createCORSRequest('GET', url);
      if (!xhr) {
        alert('CORS not supported!');
        return {};
      }
    
      xhr.onload = function() {
        var parsedResponse = JSON.parse(xhr.responseText);
        var parsedObj = renderIntradayData(parsedResponse);
         
    
        console.log(parsedObj);
        // Got the correct result here tho...
        onSuccess(parsedObj); //!--- ⚠️ ATTENTION
    
        return parsedObj;
      };
    
      xhr.onerror = function() {
        onError('Error making the request!');  //!--- ⚠️ ATTENTION
        return {};
      };
    
      xhr.send();
    }
    
    // ...

    【讨论】:

    • 谢谢伙计!现在可以了。虽然在 react 中的 setState() 之后没有绘制图表...仍然需要查看其他部分...
    • 欢迎你@TommyTang
    猜你喜欢
    • 2021-06-19
    • 1970-01-01
    • 2021-05-15
    • 1970-01-01
    • 2020-05-06
    • 2018-05-31
    • 1970-01-01
    • 2013-07-25
    • 1970-01-01
    相关资源
    最近更新 更多