HTTP SERVER GET and POST examples using JSON

Posted on
  • A simple web interface using the ESP8266 as a web server. This example sends the current buttons color to the ESPRUINO PICO and then the pico sends back the other color. (red or green) Changes the buttons color. There is a bunch of extra JSON and this is to represent multiple reads to get all of the JSON.

    <!DOCTYPE html>
    <html>
      <head>
        <title>POST GET EXAMPLE</title>
        <script>
          function response(arr,type){//arr is in JSON
            if(type==="get"){
              document.getElementById("get").style.bac­kgroundColor=arr.color;
            }else{
              document.getElementById("post").style.ba­ckgroundColor=arr.color;
            }
          }
          
          function postServer(color){
            var req = new XMLHttpRequest(),
            obj = {'color':color,'the':'rest','are':'test'­,'Red':'red','Purple':'purple','Green':'­green','Yellow':'yellow'},
            arr;
            req.open("POST","/", true);
            req.setRequestHeader("Content-type", "application/json");
            req.onreadystatechange = function(){
              if(req.readyState === 4){
                var status = req.status;
                if(status>=200 && status <300 || status === 304){
                  arr=req.responseText;
                  arr=JSON.parse(arr);
                  response(arr,"post");
                }else{
                  alert("something bad");
                }
              }
            }
            
            obj=JSON.stringify(obj);
            console.log(obj);
            req.send(obj);
          }
          function postControl(){
            var color = document.getElementById("post").style.ba­ckgroundColor;
            postServer(color);
            
          }
          
          function getServer(color){
            var req=new XMLHttpRequest(),
            arr;
            req.open("GET", "?color="+color, true);
            req.onreadystatechange = function(){
              if(req.readyState === 4){
                var status = req.status;
                if(status>=200 && status <300 || status === 304){
                  arr=req.responseText;
                  arr=JSON.parse(arr);
                  response(arr,"get");
                }else{
                  alert("something bad");
                }
              }
            }
            req.send(null);
          }
          function getControl(){
            var color = document.getElementById("get").style.bac­kgroundColor;
            getServer(color);
          }
        </script>
      </head>
      <body>
        <button style="background-color:red" id="post" type="button" onclick="postControl()">POST</button>
        <button style="background-color:red" id="get" type="button" onclick="getControl()">GET</button>
      </body>
    </html>
    
  • var page = "<!DOCTYPE html>\n<html>\n  <head>\n    <title>Sprinkler System</title>\n    <script>\n      function response(arr,type){//arr is in JSON\n        if(type===\"get\"){\n          document.getElementById(\"get\").style.b­ackgroundColor=arr.color;\n        }else{\n          document.getElementById(\"post\").style.­backgroundColor=arr.color;\n        }\n      }\n      \n      function postServer(color){\n        var req = new XMLHttpRequest(),\n        obj = {'color':color,'the':'rest','are':'test'­,'Red':'red','Purple':'purple','Green':'­green','Yellow':'yellow'},\n        arr;\n        req.open(\"POST\",\"/\", true);\n        req.setRequestHeader(\"Content-type\", \"application/json\");\n        req.onreadystatechange = function(){\n          if(req.readyState === 4){\n            var status = req.status;\n            if(status>=200 && status <300 || status === 304){\n              arr=req.responseText;\n              arr=JSON.parse(arr);\n              response(arr,\"post\");\n            }else{\n              alert(\"something bad\");\n            }\n          }\n        }\n        \n        obj=JSON.stringify(obj);\n        console.log(obj);\n        req.send(obj);\n      }\n      function postControl(){\n        var color = document.getElementById(\"post\").style.­backgroundColor;\n        postServer(color);\n        \n      }\n      \n      function getServer(color){\n        var req=new XMLHttpRequest(),\n        arr;\n        req.open(\"GET\", \"?color=\"+color, true);\n        req.onreadystatechange = function(){\n          if(req.readyState === 4){\n            var status = req.status;\n            if(status>=200 && status <300 || status === 304){\n              arr=req.responseText;\n              arr=JSON.parse(arr);\n              response(arr,\"get\");\n            }else{\n              alert(\"something bad\");\n            }\n          }\n        }\n        req.send(null);\n      }\n      function getControl(){\n        var color = document.getElementById(\"get\").style.b­ackgroundColor;\n        getServer(color);\n      }\n    </script>\n  </head>\n  <body>\n    <button style=\"background-color:red\" id=\"post\" type=\"button\" onclick=\"postControl()\">POST</button>\­n    <button style=\"background-color:red\" id=\"get\" type=\"button\" onclick=\"getControl()\">GET</button>\n  </body>\n</html>";
    /*
    server side javascript
    */
    function colorChange(data){
      var obj = {'color': null},
      color = data.color;
      if(color === "red"){
        obj.color = 'green';
      }else{
        obj.color = 'red';
      }
      return obj;
    }
    
    function pageHandler(req, res) {
      var info, data='';
      if (req.method=="POST") {
        // If it's a POST, save the data
        req.on('data',function(chunk){
          if(chunk){
            data+=chunk;
          }
          if(data.length>=Number(req.headers['Cont­ent-Length'])){
            data = JSON.parse(data);
            data = colorChange(data);
            res.writeHead(200);
            res.end(JSON.stringify(data));
          }else if(data.length>Number(req.headers['Conte­nt-Length'])){
            res.writeHead(418);
            res.end('alert("data was corrupted")');
          }
        });
      } else {
        
        // otherwise write the page out
        if (req.url=="/") {
          res.writeHead(200);
          res.end(page);
        } else {
          info = url.parse(req.url, true);
          if (info.query && "color" in info.query){
            data = colorChange(info.query);
            res.writeHead(200);
            res.end(JSON.stringify(data));
          } else {
            res.writeHead(404);
            res.end("404: Not found");
          }
        }
      }
    }
    
    //WIFI
    var WIFI_NAME = "WIFI";
    var WIFI_PASS = "password";
    
    
    digitalWrite(B9,1); // enable on Pico Shim V2
    Serial2.setup(115200, { rx: A3, tx : A2 });
    function onInit(){
      var wifi = require("ESP8266WiFi_0v25").connect(Seri­al2, function(err) {
        if (err) throw err;
        wifi.reset(function(err) {
          if (err) throw err;
          console.log("Connecting to WiFi");
          wifi.connect(WIFI_NAME, WIFI_PASS, function(err) {
            if (err) {
              onInit();
              throw err;
            }
            console.log("Connected");
            // print IP address
            wifi.getIP(console.log);
            // Create a server
            require("http").createServer(pageHandler­).listen(80);
          });
        });
      });
    }
    
    onInit();
    
  • Post a reply
    • Bold
    • Italics
    • Link
    • Image
    • List
    • Quote
    • code
    • Preview
About

HTTP SERVER GET and POST examples using JSON

Posted by Avatar for Cale @Cale

Actions