Thursday 13 April 2017

Changing json on express node.js server

I'm quite new to node.js and web development in general (so if I'm entirely off base and you have good material for me to consume I'd really like to see it).

I'm trying to prototype passing a JSON object back and forth between node.js server and http client. The client side so far looks like:

<script type="text/javascript">
document.getElementById("myBtn").addEventListener("click", passArg);

function passArg() {
    console.log("I'm here")
    var xmlhttp = new XMLHttpRequest();

    xmlhttp.open("POST", "/", true);
    xmlhttp.setRequestHeader("Content-Type", "application/json;charset=UTF-8");

    xmlhttp.onreadystatechange = function() {
        if (xmlhttp.readyState == XMLHttpRequest.DONE ) {
           if (xmlhttp.status == 200) {
                //var json = JSON.parse(xmlhttp.responseText);      
           }
           else if (xmlhttp.status == 400) {
              alert('There was an error 400');
           }
           else {
               alert('something else other than 200 was returned');
           }
        }
    }

    var data = JSON.stringify({"email":"hey@mail.com","password":"101010"});    
    xmlhttp.send(data);
    get_json(); 
}

function get_json(){
    console.log("getting json");
    var xmh = new XMLHttpRequest();

    xmh.open("GET", "/playlist/playlist.json", true);
    xmh.send();

    xmh.onreadystatechange = function() {
        if (this.readyState == this.DONE ) {
           if (this.status == 200) {
                var json = JSON.parse( this.responseText );
                console.log(json.email + " "+ json.password + " " + json.access_date); 
           }
           else if (xmh.status == 400) {
              alert('There was an error 400');
           }
           else {
               alert('something else other than 200 was returned');
           }
        }
    }


}
</script>

And the server side is coded as

app.post("/", function (req, res) {
    console.log('Request received');

    req.on('data', function (chunk) {
        console.log('GOT DATA!');
        json = JSON.parse(chunk);
        json.access_date  =  "12.04.17";

        write_json(json)
        console.log("finished writing- in app_post")
    });

    console.log("passing all clear to client")
    res.writeHead(200);

    res.send();

})

function write_json(chunk){
    console.log("WHADDUP")
    console.log(JSON.stringify(chunk))
    fs = require("fs")
    var filename = "./public/playlist/playlist.json";
    var file = require(filename);

    file = chunk;

    fs.writeFile(filename, JSON.stringify(file), function(err){  
        if (err) return console.log(err);
            console.log(JSON.stringify(file));
            console.log('writing to ' + fileName);
        }
    )
    console.log("finished writing - in write_json")
    }

On the serverside console the following output is generated

Request received
passing all clear to client
GOT DATA!
WHADDUP
{"email":"hey@mail.com","password":"101010","access_date":"12.04.17"}
module.js:428
    throw err;
    ^

SyntaxError: public/playlist/playlist.json: Unexpected end of input

And on the client side of things the console reads

(index):15 I'm here
(index):41 getting json
(index):45 GET http://localhost:8080/playlist/playlist.json net::ERR_CONNECTION_RESET

From this I read that the asynchronous POST event is sending the all clear to call get_json before the file itself is updated. And it seems the updating of the file on the server side isn't working as well. How do I structure the calls to make the edit quite smooth?



via Copperwire

No comments:

Post a Comment