I am trying to call a REST API hosted locally using CORS, and fetch the data to visualize on my front-end wrote using React. But I keep getting undefined from the data fetch function, and the function works well when I console out the data in the 'onload' handler. Here are my two scripts doing data fetching:
// 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 is an asynchronous function . Then , you need to pass a callback to be running when the response comes .
So, the first change is the signature of fetch function :
export function fetchIntradayDataHR(url, onSuccess, onLoad) {}
instead of
export function fetchIntradayDataHR(url) {}
Then in the React Component, you will call this function accordingly and the callback will includes 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);
instead of
var url = "http://127.0.0.1:8080/heart";
// var response = fetchIntradayDataHR(url);
console.log(fetchIntradayDataHR(url));
this.setState({ ... });
Brief you code can as the following :
// 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();
}
// ...
Related
In JS, I wanted to create a function that made a xHTMLRequest to a backend PHP server, problem is I want JS to wait for the response, otherwise it will display 'undefined'.
function xhrReq(method, args) {
let xhr = new XMLHttpRequest();
xhr.open(method, 'http://localhost/example/php/example.php');
xhr.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
xhr.send(args);
xhr.onreadystatechange = ()=> {
if(xhr.readyState == 4) {
return xhr.response;
}
}
How can I make this function return the response value?
You can use fetch in a async function:
(async () => {
try {
//const args = ...;
var headers = new Headers();
headers.append("Content-Type", "application/x-www-form-urlencoded");
const response = await fetch('http://localhost/example/php/example.php', {
method: 'POST', // or other
headers,
body: args
});
} catch (err) {
//process error
}
})()
or you can promisify your function :
function xhrReq(method, args) {
return new Promise(function(resolve, reject) {
var xhr = new XMLHttpRequest();
xhr.open(method, 'http://localhost/example/php/example.php');
xhr.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
xhr.onload = function() {
if (xhr.status === 200) {
resolve(xhr.response);
} else {
reject(Error(`XHR request failed. Error code: ${xhr.statusText}`));
}
};
xhr.onerror = function() {
reject(Error('There was a network error.'));
};
xhr.send(args);
});
}
And use it in a async function (or use promise) to get the response.
I want to use a variable which has the JSON data to later parse and stringify it
all i want now is to see the actual array of objects in the console!
console.log(fetchJSON('url'));
function fetchJSON(url, cb) {
const xhr = new XMLHttpRequest();
xhr.open('GET', url);
xhr.responseType = 'json';
xhr.onload = () => {
if (xhr.status < 400) {
cb(null, xhr.response);
} else {
cb(new Error(`Network error: ${xhr.status} - ${xhr.statusText}`));
}
};
xhr.onerror = () => cb(new Error('Network request failed'));
xhr.send();
}
I expect the output of console.log(fetchJSON('url'));
to be
Try this:
fetchJSON('url', function(result) {
console.log(result);
});
Your function fetchJSON is returning a callback function. If you want to return just the result change
this
cb(null, xhr.response);
to:
return xhr.response;
I want to fire an http API and process it's response but I am getting following error:
Exception while executing function: Functions.getAccessObject. mscorlib: ReferenceError: XMLHttpRequest is not defined
Here's my Azure serverless function Code:
module.exports = function (context, req) {
function getAccessObject(context, successCallback, failureCallback) {
var APPLICATION_ID = "zzz";
var APPLICATION_SECRET = "zzz";
var REFRESH_TOKEN = "zzz";
var xhr = new XMLHttpRequest();
xhr.withCredentials = true;
xhr.open("GET", "https://xyz");
xhr.setRequestHeader("applicationid", APPLICATION_ID);
xhr.setRequestHeader("applicationsecret", APPLICATION_SECRET);
xhr.setRequestHeader("refreshtoken", REFRESH_TOKEN);
xhr.setRequestHeader("cache-control", "no-cache");
xhr.onreadystatechange = function() {
if (request.readyState === 4) {
if (request.status === 200) {
successCallback(context, request.responseText);
} else {
failureCallback(context, request.responseText);
}
}
};
request.send(null);
}
getAccessObject(context, registerForWebhookFunc, failureCallbackFunc);
}
I believe XHR is a browser API and not native to node.js. You can use the built-in http functionality of node.js (see example below) or alternatively other popular packages are available such as Axios that can do http requests. I believe there may even be one for XHR if you are set on using that.
const https = require('https');
https.get('http://myapi', (resp) => {
let data = '';
resp.on('data', (chunk) => {
data += chunk;
});
resp.on('end', () => {
console.log(JSON.parse(data));
});
}).on("error", (err) => {
console.log("Error: " + err.message);
});
}
I just started making use of the promise function in javascript, and i do like it, but i am running into an issue.
I am getting a value from a promise object, and then sending the response back to the server in an asynchronous promise function. When i send the value back to the server, and try to see what the value is, it returns undefined.
var xhr = new XMLHttpRequest();
function createFirstChannel(method, rippleApi) {
return new Promise(function (resolve, reject) {
xhr.open(method, url, true);
xhr.setRequestHeader("Content-Type", "application/json");
xhr.onload = function () {
if (xhr.readyState == 4 ) {
var hashValue = resolve(JSON.parse(xhr.responseText));
}
else {
reject({
status: this.status,
statusText: xhr.statusText
});
}
};
xhr.onerror = function () {
reject({
status: this.status,
statusText: xhr.statusText
});
};
xhr.send(json);
});
}
A value gets returned from the first function which i am using in the next promise function
async function createChannel(method, url) {
var datums = await createFirstChannel(method, url);
//method to return hash value from json request
for (var key in datums) {
var tx_json = datums[key]['json'];
datums = (json['hash']);
console.log(datums);
}
//creating the json request to send back out again using POST METHOD
var channel= {
"method": "tx",
"par": [{
"transaction": datums
}]
}
var jsonPayee = JSON.stringify(channel);
xhr.open(method, url, true);
xhr.setRequestHeader("Content-Type", "application/json");
xhr.onload = function () {
if (xhr.readyState == 4) {
users = JSON.parse(xhr.responseText);
}
};
xhr.send(jsonPayee);
return users;
}
createChannel(method, url).then(datums => {
console.log(datums);
}).catch(function (err) {
console.error('Sorry There Was An Error!', err.statusText);
});
i get "undefined" response at console.log. is there any way to resolve this error? Thanks for the help
I'm facing an issue with promises..and was banging my head around from almost an hour now...
this.getDocument(documentId)
.then(function (response) {
console.log('in first then')
return 'from first then';
}).then(function (response) {
console.log(response)
});
Ideally the above code should give following output
in first then
from first then
But the actual output is as follows
in first then
undefined
Now the problem here is why the second then is getting response as undefined when I'm returning something from the first then.
[EDIT 1] Adding getDoument code
function getDocument(documentID) {
var config = {
url: '<URL>' + documentID,
headers: {enter code here
'Content-Type': 'application/json'
}
};
return HttpRequest.get(config);
}
var HttpRequest = (function () {
function HttpRequest() {
}
HttpRequest.get = function (config) {
var deferred = Q.defer();
var http = new XMLHttpRequest();
var url = config.url;
var authToken = window.localStorage.getItem('token');
http.open("GET", url, true);
Object.keys(config.headers).map(function (k) {
http.setRequestHeader(k, config.headers[k]);
});
http.setRequestHeader("Authorization", 'Bearer ' + authToken);
http.onreadystatechange = function () {
if (http.readyState !== 4)
return;
var response = http.responseText;
if (http.status != 200)
return deferred.reject(response);
deferred.resolve(response);
// if (/^[^2]\d\d$/.exec(http.status)) return deferred.reject(http.status);
};
http.send();
return deferred.promise;
};
HttpRequest.post = function (config) {
};
return HttpRequest;
}());