Saturday, 3 June 2017

Why im getting error?

HI I am getting this error:

Error is:SyntaxError: Unexpected token ' in JSON at position 0 '{username:xyz,password:xyz}'

when i am calling server with this command:

{curl -H "Content-Type: application/json" -X POST -d '{"username":"xyz","password":"xyz"}' http://localhost:8080

And my code is this:

var http = require('http');

function handle_incoming_request(req,res) {
console.log("Incoming Request:("+ req.method + ")" + req.url);
var json_data = "";

req.on(
    "readable",
    function(){
        var d = req.read();
        if(typeof d == 'string')
        json_data += d;
        else if(typeof d == 'object' && d instanceof Buffer)
        json_data += d.toString("utf8");
    });

    req.on(
        "end",
        function(){
            var out = "";
            if(!json_data)
            out = "I am no JSON"
            else {
                var json;
                try {
                    json = JSON.parse(json_data.toString("utf8"));
                } catch (err) {
                    console.log("Error is:" + err + "\n" + json_data);
                }
                if(!json)
                out = "Inavlid JSON" + json;
                else 
                out = "Valid JSON" + json_data;
            }
            res.end(out);
        }

    );
}


var s = http.createServer(handle_incoming_request);
s.listen(8080);



via Praveen Cool

No comments:

Post a Comment