来自React中的CORS API调用未定义

时间:2017-07-10 21:05:53

标签: javascript reactjs cors frontend backend

我正在尝试使用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();
}

// ...

1 个答案:

答案 0 :(得分:2)

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

所以,第一个改变是获取函数的签名:

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

// ...