http.request not working on Espruino Wifi

Posted on
  • Hi all,
    I can for the life of me not get the http.request to work but the http.get works just fine. Please see the code I use below. The http.request just does nothing, seemingly the callbacks don't get fired at all.
    I played around with all kind of different options, but none seem to work. I'm puzzled... once again.

    var wifi = require("Wifi");
    var WIFI_NAME = "xxxx";
    var WIFI_OPTIONS = {
      password: "yyyyy"
    };
    var http = require("http");
    
    function onInit() {
      print("connecting...");
      // Connect to WiFi
      wifi.connect(WIFI_NAME, WIFI_OPTIONS, err => {
      if (err !== null) {
        throw err;
      }
      // Print IP address
      wifi.getIP((err, info) => {
        if (err !== null) {
          throw err;
        }
        print("http://"+info.ip);
            
        //works
        simpleGet();
        
        //doesn't work
        requestGet();
        
      });
    });
    }
    
    function simpleGet(){
      http.get("http://www.pur3.co.uk/hello.tx­t", function(res) {
      res.on('data', function(data) {
        console.log(data);
      });
    });
    }
    
    function requestGet(){
      var options = {
        host: 'http://www.pur3.co.uk',
        protocol: 'http:',
        port: 80,
        path: '/',
        method: 'GET',
      };
      http.request(options, function(res) {
      res.on('data', function(data) {
        console.log(data);
      });
      res.on('close', function(data) {
        console.log("Connection closed");
      });
    }); 
    }
    
  • Mon 2020.01.27

    @Raik, untested but was the note immediately above the snippet observed?

    "Description
    Create an HTTP Request - end() must be called on it to complete the operation."

    http://www.espruino.com/Reference#t_l_ht­tp_request

    See sample in 'POST' example:

    http://www.espruino.com/Internet

  • Ahh yes, that did it, thanks!
    I was looking at the http.request reference and basically tried using the code there , which has no call to end.

  • Glad you got it sorted! I'll get the reference updated

    edit: The reference did actually mention .end, but it definitely sh ould have had it in the example :) There's a good example of using HTTP POST here if you're interested as well: https://www.espruino.com/Internet#http-p­ost

  • Post a reply
    • Bold
    • Italics
    • Link
    • Image
    • List
    • Quote
    • code
    • Preview
About

http.request not working on Espruino Wifi

Posted by Avatar for Raik @Raik

Actions