Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get POST data and return with res.end() - encoding issue

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.

like image 309
f1nn Avatar asked Jul 04 '26 01:07

f1nn


2 Answers

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.

like image 104
travis Avatar answered Jul 06 '26 13:07

travis


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

like image 23
cathy.sasaki Avatar answered Jul 06 '26 15:07

cathy.sasaki



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!