Sunday, 12 March 2017

Client side can not take the json data

I have a nodejs server and the code that I have as below. I send an AJAX request and I want the server to send me a response of a json data. When I put res.write()("string data like hello hello") in the server code, client side can take the value of inside and I can see the value on the console. But I cannot get json value with this function. I tried res.end() and res.send() functions as well but it didn't work. How can I send the json value and the following client side code can take the value correctly?

Server side,

app.use('/', function(req, res) {
console.log("req body app use", req.body);
var str= req.path;

if(str.localeCompare(controlPathDatabaseLoad) == 0)
{
    console.log("controlPathDatabaseLoad");
    mongoDbHandleLoad(req, res);
    res.writeHead('Content-Type', 'application/json');
    res.write("Everything all right with database loading"); //I can get this message
    //res.end(json) I can not get json message with this function as well
    res.send("OK");
    //res.send(JSON.stringify(responseBody)); I can not get json message
}

Client side,

function loadDatabaseData()
    {
        console.log("loadDatabaseData");
        var oReq = new XMLHttpRequest();
        oReq.open("GET", "http://192.168.80.143:2800/load", true);
        oReq.setRequestHeader("Content-type", "application/json;charset=UTF-8");
        oReq.onreadystatechange = function() {//Call a function when the state changes.
            if(oReq.readyState == 4 && oReq.status == 200) {
                console.log("http response", oReq.response);
                console.log("http responseText", oReq.responseText);
            }
        }
        oReq.send();

    }



via zoint

No comments:

Post a Comment