简体   繁体   English

发送到CouchDB时,Json不是很好

[英]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. 当使用node.js作为代理来防止xss问题时,我遇到了向前发送json的问题。

Whilst logging the data received I couldn't find any problems. 记录收到的数据时,我找不到任何问题。

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. 当我编写另一个显示收到数据的node.js服务器时,解决方案来找我,我让它模仿CouchDB服务器。

It turned out to be a non ascii character (Swedish-Å) that was the culprit. 事实证明,这是一个非ascii角色(Swedish-Å)是罪魁祸首。 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. 解决方案是在计算Content-Length之前使用Buffer将原始数据转换为utf8。

     :
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();
    });
}
    :

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM