Reading data from res.end()

I'm sending a simple data back from the server to the client.

app.post('/user', function (req, res) { 
    var userName = "John";
    res.end(JSON.stringify({"error":"", "user": userName}));
});


$.ajax({
    type: "POST",
    ...
    contentType : 'application/json',
    dataType: "json"
})
    .done(function(data) {
        // send join message
        var resData = JSON.parse(data);
        alert("hello"); // this doesn't show up
        });
    });
});

But in the browser console, I get this error - "Uncaught SyntaxError: Unexpected token o".

If I do JSON.stringify and JSON.parse on the content, it works fine.

alert(JSON.parse (JSON.stringify({"error":"", "user": userName})).user); 

And also, .done works fine without a data payload from the server i.e. the alert("hello") works.

So, I'm guessing something fishy is happening while sending data within res.end(). Please help.

While at it, it would be nice if you can also tell me how to do the same using res.json() and which one is preferable.

The problem here is that you set dataType: 'json' in your jQuery request. This causes the response from the server to be automatically parsed as JSON, so it will return the object rather than the raw server response.