javabeangrinder
javabeangrinder

Reputation: 7159

Not well formed Json when sending to CouchDB

I had a problem with sending json forward when using node.js as a proxy to prevent xss problems.

Whilst logging the data received I couldn't find any problems.

Upvotes: 1

Views: 833

Answers (1)

javabeangrinder
javabeangrinder

Reputation: 7159

The solution came to me when I wrote another node.js server that displayed the data received and I let that mimic the CouchDB server.

It turned out to be a non ascii character (Swedish-Å) that was the culprit. The data received was treated as raw calculating the Content-Length badly, or correct depending on your mood. ;)

The solution was to use a Buffer to convert the raw data into utf8 before calculating Content-Length.

     :
if (request.method == 'PUT') {
    var data = '';
    request.on('data', function(dataSnippet) {
        data += dataSnippet;
        if (data.length > 1e6) {request.connection.destroy();}
    });
    request.on('end', function(dataSnippet) {
        data = new Buffer(data, 'UTF8');     //<---  This is the solution
        options.headers = {
            'Content-Encoding': 'UTF8',
            'Content-Type': 'application/json',
            'Content-Length': data.length    //<---  Where it went wrong
        }
        proxy = http.request(options, function(proxy_response) {
            proxy_response.setEncoding('UTF8');
            proxy_response.pipe(response);
        });
        proxy.write(data);
        proxy.end();
    });
}
    :

Upvotes: 3

Related Questions