I am rewriting a small python script in node.js. The original script worked as follows:
import urllib
import httplib
import json
def rpc(url, args = { }):
try:
post_data = json.dumps({'args': args})
f = urllib.urlopen(url, post_data)
if not f or f.code != 200:
return { 'result': 1, 'error': 'urlopen returned error' }
data = f.read()
js_data = json.loads(data)
except Exception, e:
return { 'result': 2, 'error': e }
else:
return { 'result': 0, 'data': js_data }
print rpc('http://server.local/rpc', {'x': u''})
I use request to do the same in node.js:
var request = require('request')
request.post('http://server.local/rpc', {
json: {'x': ''}
}, function(err, result) {
console.log(err, result.body)
})
It works, but the data in unicode is distorted, so when I request data, I get ÑеÑÑinstead . It seems strange considering that both python and node.js should send data encoded in utf8.
Btw, the server is written in Perl, I think, but all I know about it: (
In addition, the server returns Unicode data for other requests, therefore can do it.
Upd. my console prints Unicode characters perfectly.
Upd. Rewrote my code to use the node.js module http:
var http = require('http')
var options = {
hostname : 'server.local',
path : '/rpc',
method : 'POST'
}
var req = http.request(options, function (res) {
res.setEncoding('utf8');
res.on('data', function (chunk) {
console.log('BODY: ' + chunk);
});
});
var body = JSON.stringify({'x': ''})
req.setHeader('Content-length', body.length)
req.setHeader('Content-type', 'application/x-www-form-urlencoded')
req.on('error', function (e) {
console.log('problem with request: ' + e);
});
req.end(body, 'utf8');
, , . ( MBA Debian). , , node.js Unicode.