Details on HTTP request object

Posted on
  • Hi all,

    first of all let me know that I am super impressed by espruino. I got 4 kickstarter boards including the CC3000 adafruit wifi breakout and creating a server plus responding to requests and serving some JSON response etc. is in total super smooth - compared to other options out there.

    I have one question though. Below is the full createServer code, but the code snippet I really don't like right now is this:

    	  if(req.url.substr(0,2) == "/?")
          	digitalWrite(C15, (req.url.indexOf('led=true') != -1));
    

    based on a call to the root resource / I am determining whether to turn an LED on or off. To my knowledge, there is no automatic req.queryString object for example that would give you the queryString. Even better would be to get a pre-parsed map of the querystrings, then I could do:

    if (req.params.led == 'true')
     -> do stuff
    

    The way I found the url property is by JSON.stringifying the req object and that one is pretty large. I might have overlooked something, but I could not find more specific ways to access the path of the call or the queryString and parameters.

    Is this planned to be added or somewhere where I just did not find it?

    Thx
    Sven

    wlan.connect( "xxx", "xxx", function (s) { 
      if (s=="dhcp") {
        console.log("My IP is "+wlan.getIP().ip);
        require("http").createServer(function (req, res) {
          //turn LED on/off
          console.log(req.url);
          
    	  if(req.url.substr(0,2) == "/?")
          	digitalWrite(C15, (req.url.indexOf('led=true') != -1));
          
          var obj = {};
          obj.success = true;
          obj.poti = analogRead(A1);
          
          res.writeHead(200, {'Content-Type': 'application/json'});
          //res.write("{\"success\":true, \"val\":"+analogRead(A1)+"}");
          res.write(JSON.stringify(obj));
          res.end();
        }).listen(80);
      }
    }); 
    
  • Hi Sven,

    Thanks - I do show URL being used in the examples for a web server, but the current solution isn't great. I've just found that in node you can do url.parse(req.url,true) which should give you all the info you need (http://nodejs.org/docs/latest/api/url.ht­ml). While Espruino has this implemented, it doesn't parse the query string, which is what you need. I've created a bug for this and hopefully I'll get around to fixing it soon.

    In the mean time, you can try something like this:

    function parseURL(url) {
      var idx = url.indexOf("?");
      var map = {};
      if (idx>=0) {
        var args = url.substr(idx+1).split("&");
        for (var n in args) {
          var arg = args[n];
          var eq = arg.indexOf("=");
          if (eq<0) eg=arg.length;
          map[arg.substr(0,eq)] = arg.substr(eq+1);
        }
      }
      return map;
    }
    
    parseURL("/hello?key=val&foo=bar&somethi­ng");
    // ={"key":"val","foo":"bar","something":''­}
    
  • ... a small typo in line 9.

    if (eq<0) eg=arg.length;
    

    should be

    if (eq<0) eq=arg.length;
    
  • I am using this code in a slightly modified version.

    function parseUrl(url) {
    	var idx = url.indexOf("?");
    	var data = {
    		path:"",
    		param:{}
    	};
    	
    	if (idx >= 0) {
    		var args = url.substr(idx + 1).split("&");
    		
    		for (var n in args) {
    			var arg = args[n];
    			var eq = arg.indexOf("=");
    			
    			if (eq < 0) {
    				eq = arg.length;
    			}
    			
    			data.param[arg.substr(0, eq)] = arg.substr(eq + 1);
    		}
    		
    		data.path = url.substr(0, idx);
    	} else {
    		data.path = url;
    	}
    	
    	return data;
    }
    

    This way i get a JSON Object with path and parameter.

    parseURL("/hello?key=val&foo=bar&somethi­ng");
    //{"path":"/hello","param":{"key":"val",­"foo":"bar","something":''}}
    
  • Just to say (sorry I didn't update you on this) that I've added proper URL parsing now:

    >url.parse("/hello?key=val&foo=bar&somet­hing",true)      
    ={"method":"GET","host":"","path":"/hell­o?key=val&foo=bar&something","pathname":­"/hello","search":"?key=val&foo=bar&some­thing","port":80,"query":{"key":"val","f­oo":"bar","something":""}}
    

    Having said that I tried it and it's broken on 1v50 - so you'll have to wait until 1v51 comes out anyway! :)

  • Hi Gordon,
    thanks for the update.

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

Details on HTTP request object

Posted by Avatar for hansamann @hansamann

Actions