Chat freely about the open source Javascript projects for ESP8266

User avatar
By hygy
#32008 That is better. But if I need to resolv the name separated and give use the get call with ip address, then I cannot use sites with virtual hosts (as my own server user apache2 virtual hosts).
User avatar
By Erni
#32021 Looking at the example page, I just saw a new feature (I think it is new) called getHostByName.
If you use this with hostname http://www.eecs.mit.edu, you get the correct ip-number 18.62.0.96.
A big thanks to the developers for this

Code: Select allESP8266WiFi.init();
var hostname="www.eecs.mit.edu";
 
ESP8266WiFi.getHostByName(hostname, function(data){
  print(ESP8266WiFi.getAddressAsString(data));
});


So, to fetch the indexpage:

Code: Select allESP8266WiFi.init();

var hostname="www.eecs.mit.edu";
var ipn;

ESP8266WiFi.getHostByName(hostname, function(data){
  print(ESP8266WiFi.getAddressAsString(data));
 ipn=ESP8266WiFi.getAddressAsString(data);
});

var http = require("http");
http.get({
    host: ipn,
    port: 80,
    path: "/"
}, function(response) {
    print("get callback!");
    response.on('data', function(data) {
      print(data);
    });
    response.on('close', function() {
       print("The response connection closed");
    });
});
User avatar
By kolban
#32043 I think there may need to be a slight modification to the code. In JavaScript, we use callback functions to indicate when something has completed. JavaScript programs (in the browser and on ESP8266) shouldn't be blocking. This means when we want to perform something that takes time (and time is relative here ... 10's of milliseconds is a long time) we register a callback.

So when we call

Code: Select allESP8266WiFi.getHostByName("www.google.com", function(ipAddress) {
   // Do something with the ip address
});


Then the ipAddress isn't known until the callback returns.

If we code globals:

Code: Select allvar myDesiredIp;
ESP8266WiFi.getHostByName("www.google.com", function(ipAddress) {
   myDesiredIp = ipAddress;
});
// (A) ... do some code here


Then what happens is that a request to get the IP address is made and then immediately we reach point (A) in the execution. However, this does not mean that the callback from getHostByName has been executed. It might ... but it is as likely as not to not have been ... in which case "myDesiredIp" will be currently unset.

In JavaScript, using globals is not necessarily the right way to go. Instead ... we would want some code similar to:

Code: Select allESP8266WiFi.getHostByName("www.google.com", function(ipAddress) {
   // (A) ... do some code here
});


The philosophies of JavaScript are different from those of procedural oriented languages like C.