从 React 中的 CORS API 调用中得到 undefined

Got undefined from the CORS API call in React

我正在尝试使用 CORS 调用本地托管的 REST API,并获取数据以在我使用 React 编写的前端上可视化。但是我一直从数据获取函数中得到 undefined,当我在 '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();
}

// ...

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();
}

// ...