The problem is that I want to print out myGlobalData which is the response to a fetching of data from a REST API, and later use it for generation of HTML.
I notice that I am able to print out the myLocalData to console.log, however am unable to print out the myGlobalData with console.log.
The problem is that the myGlobalData is unDefined.
Why is the myGlobalData result undefined? I have assigned the myGlobalData inside the mydata.then function to the text result, just like the myLocalData function.
Why is the myGlobalData unDefined, and the myLocalData a valid text response?
var fetch = require("node-fetch");
var http = require("http");
var express = require('express');
var app = express();
var bodyParser = require('body-parser');
var urlencodedParser = bodyParser.urlencoded({ extended: true });
let myGlobalData;
// Running Server Details.
var server = app.listen(8082, function () {
var host = server.address().address
var port = server.address().port
console.log("Example app listening at %s:%s Port", host, port)
});
app.get('/form', function (req, res) {
var html='';
html +="<body>";
html += "<form action='/thank' method='post' name='form1'>";
html += "web URL:</p><input type='text' name='weburl'>";
html += "<input type='submit' value='submit'>";
html += "<INPUT type='reset' value='reset'>";
html += "</form>";
html += "</body>";
res.send(html);
});
app.post('/thank', urlencodedParser, function (req, res){
var reply='';
var mydata = fetch('https://facebook.github.io/react-native/movies.json');
mydata.then(function(response) {
return response.text()
}).then(function(text) {
// var myLocalData = text;
myGlobalData = text;
myLocalData = text;
console.log(myLocalData);
});
console.log(myGlobalData); // result is undefined Why?