Possible to get HTTP headers?

Posted on
  • Following code sample fails:

    var wifi = require("EspruinoWiFi");
    var http = require('http');
    
    wifi.connect('yourAP', { password: 'yourPass' }, function(err) {
      if (err) { throw err; }
      
      wifi.getIP(function (err, data) {
        if (err) { throw err; }
    
        console.log(data);
        
        var options = {
          host: 'espruino.com',
          port: 80,
          path: '/',
          method: 'HEAD',
        };
    
        console.log('about to http request');
        http.request(options, function(res) {
          console.log('request cb');
          res.on('data', function(data) {
            console.log("HTTP> "+data);
          });
    
          res.on('close', function(data) {
            console.log(data);
            console.log("Connection closed");
          });
    
          res.on('error', function(err) {
            console.log(err);
          });
        }).end();
      });
    });
    
    

    Produces only:

    about to http request
    request cb
    false
    Connection closed

    Change it to a GET request and you get:

    about to http request
    request cb
    HTTP> <!DOCTYPE HTML PUBLIC "-//IETF//DTD HTML 2.0//EN">
    >


    Moved Permanently


    The docu
    HTTP> ment has moved here.




    s>Apache/2.4.18 (Ubuntu) Server at espruino.com Port 80
    tml>
    false
    Connection closed

    but I want the HTTP headers not the content.

  • The headers should be in res anyway? The callback only gets called once the headers have been parsed.

    By the way, I'll be on holiday next week, so I won't be able to answer any of your posts now until I get back.

  • Don't blame you Gordon, its a full-time job just supporting my forum posts ;)

  • 
    function onPageRequest(req, res) {
    
    	var a = url.parse(req.url, true);
    	console.log(a);
    
      console.log(req.headers);
      console.log(req.method);
    

    headers:

    {
      "Host": "192.168.1.13",
      "Connection": "keep-alive",
      "Cache-Control": "max-age=0",
      "Upgrade-Insecure-Requests": "1",
      "User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/58.0.3029.96 Safari/537.36",
      "Accept": "text/html,application/xhtml+xml,applica­tion/xml;q=0.9,image/webp,*/*;q=0.8",
      "Accept-Encoding": "gzip, deflate, sdch",
      "Accept-Language": "en-GB,en-US;q=0.8,en;q=0.6"
     }
    
  • Yup perfect, thanks +Wilberforce, I completely forgot about the .headers prop.

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

Possible to get HTTP headers?

Posted by Avatar for dave_irvine @dave_irvine

Actions