At this moment I am able to do curl -X GET 127.0.0.1:8081/flower in my command prompt and receive my JSON like I was expecting.
However, whenever I try to do the same GET request to the same exact URL from my code, I get undefined in every way I try. Below is my code for javascript and node.js. I would like to save the responseText to a global variable to be able to be saved as an array.
This is my HTTP request to pull the JSON request from the server:
function apiCall() {
var menuRqst = new XMLHttpRequest;
menuRqst.open('GET', 'http://127.0.0.1:8081/flower', true);
menuRqst.send();
menuRqst.addEventListener('readystatechange', processRequest, false);
function processRequest(d) {
if (menuRqst.readyState === 4 && menuRqst.status === 200) {
var flowResponse = menuRqst.responseText;
return flowResponse;
}
}
}
This is my node.js where I can curl -X GET 127.0.0.1:8081/flower and receive the data found in flower.JSON as a response:
var express = require('express');
var app = express();
var fs = require("fs");
app.get('/flower', function (req, res) {
fs.readFile(__dirname + "/" + "flower.json", 'utf8', function (err, data) {
console.log(data);
res.end(data);
});
})
var server = app.listen(8081, function () {
var host = server.address().address
var port = server.address().port
console.log("Example app listening at http://%s:%s", host, port)
})
It's all about asynchrony.
apiCallis not returning anything.Also, what's more you should find a way to prepare the response when is ready, probably wrapping a
Promiseat the start ofapiCall.Also, if this is browser code, you may want to try out
fetchand useasync/await.With fetch: