我正在用node.js 重写一个小的python 脚本。原来的脚本是这样工作的:
# -*- coding: utf-8 -*-
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 https://github.com/mikeal/request在 Node.js 中执行相同操作:
var request = require('request')
request.post('http://server.local/rpc', {
json: {'x': 'тест'}
}, function(err, result) {
console.log(err, result.body)
})
它可以工作,但是 unicode 数据是乱码,所以我得到ÑеÑÑ
代替тест
查询回数据时。
这看起来很奇怪,因为 python 和 node.js 都应该发送 utf8 编码的数据。
顺便说一句,我认为服务器是用 perl 编写的,但这就是我所知道的:(
此外,服务器在其他查询上返回 unicode 数据,因此它is能够做到这一点。
更新。我的控制台可以很好地打印 unicode 字符。
更新。重写我的代码以使用node.jshttp
module:
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)
// python sends data with this header
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 数据的方式有关。