I'm sending POST data from Python program to Node.JS-server and return with res.end. Here's the python code:
#! /usr/bin/env python
# -*- coding: utf-8 -*-
import requests
value = u"Этот текст в кодировке Unicode"
url = "http://localhost:3000/?source=test"
headers = {'content-type': 'text/plain; charset=utf-8'}
r = requests.post(url, data=value.encode("utf-8"))
print r.text
And here's how I process data in Node.JS:
http.createServer(function(req, res) {
req.setEncoding = "utf8"
var queryData = '';
if (req.method == 'POST') {
req.on('data', function(data) {
queryData += data;
});
req.on('end', function() {
res.writeHead(200, {
'Content-Type': 'text/plain'
});
res.end(queryData)
});
} else {
// sending '405 - Method not allowed' if GET
res.writeHead(405, {
'Content-Type': 'text/plain'
});
res.end();
}
}).listen(3000, '127.0.0.1');
As result I get:
$ python test.py
ÐÑÐ¾Ñ ÑекÑÑ Ð² кодиÑовке Unicode
How should I set encoding properly to get "Этот текст в кодировке Unicode" as a result? Thanks.
You need to set the charset of the returning data:
res.writeHead(200, {
'Content-Type': 'text/plain; charset=utf-8'
});
At the top you are setting the "decoding" of the coming data, but never set the out going response.
setEncoding in Node.JS is a method so instead of = use the following:
req.setEncoding('utf8');
See example here: http://nodejs.org/api/http.html