4

如果我在未注释“setEncoding”行的情况下运行以下代码,则会收到以下错误:

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

res.setEncoding('utf8');

    ^

TypeError: Object # has no method 'setEncoding'

没有这条线,一切都按预期工作——除了浏览器抱怨未声明的字符编码。

文档、SO、GitHub 问题列表或广泛的谷歌搜索中没有任何有用的东西。node.js 最新版本: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);
4

2 回答 2

8

http.ServerResponse类没有 setEncoding 方法。您试图设置标题“字符集”,但“字符集”是“内容类型”标题的一部分。尝试这个:

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

请记住,这只是为客户提供有关如何解释内容的信息,而不是规则。

于 2012-08-12T20:39:09.377 回答
0

对于在 TypeScript 中遇到相同问题的任何人,您应该使用类型 https.ClientRequest 而不是 Request。

于 2018-05-12T08:53:09.867 回答