gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-30 11:34:34 27 4
gpt4 key购买 nike

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

// ...

最佳答案

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

// ...

关于javascript - 从 React 中的 CORS API 调用中得到 undefined,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45021586/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com