Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

node.js setEncoding issue

Tags:

node.js

If I run the code below with the "setEncoding" line uncommented, I receive the following error:

/usr/local/test-server/test.js:78

res.setEncoding('utf8');

    ^

TypeError: Object # has no method 'setEncoding'

Without that line, everything works as expected - except for browsers complaining about undeclared character encoding.

Nothing in the docs, SO, the GitHub issues list, or extensive Googling have turned up anything useful. node.js version is the latest: 0.8.6

var https = require('https');
var sslPrivateKey = fs.readFileSync('./pk.pem');
var sslCert = fs.readFileSync('./cert.pem');
var sslOpts = { key: sslPrivateKey, cert: sslCert };

var server = https.createServer(sslOpts, function(req, res) {

    if ('GET' === req.method) {

        res.writeHead(200, {'Content-Type': 'text/plain','charset': 'utf8'});
        //res.setEncoding('utf8');
        res.write('You are here' + "\n");
        res.end();

    } 

}

server.listen(8080);
like image 515
J B Avatar asked Feb 20 '23 12:02

J B


1 Answers

Class http.ServerResponse has no setEncoding method. You trying to set header 'charset' but 'charset' is part of 'Content-Type' header. Try this:

res.writeHead(200, {'Content-Type': 'text/plain; charset=utf8'});

Remember that this is just information for client about how to interpret the contents, not rule.

like image 81
Vadim Baryshev Avatar answered Feb 28 '23 11:02

Vadim Baryshev