【发布时间】: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