为什么我不能在nodejs HTTP响应中写中文字符?

这是我的小代码:

var http = require('http'); var port = 9002; var host_ip = '<my_ip>'; http.createServer(function (req, res) { var content = new Buffer("Hello 世界", "utf-8") console.log('request arrived'); res.writeHead(200, { 'Content-Encoding':'utf-8', 'charset' : 'utf-8', 'Content-Length': content.length, 'Content-Type': 'text/plain'}); res.end(content.toString('utf-8'),'utf-8'); }).listen(port, host_ip); console.log('server running at http://' + host_ip + ':' + port); 

以前我只是让res.end发送“你好世界”,它运作良好。 然后我想稍微调整一下,把“世界”改成中文的“世界”,把标题中的“charset”内容types改为“utf-8”。 但在Chrome和Firefox中,我看到了这一点:

 hello 涓栫晫 

然而,惊人的歌剧(11.61)确实显示了正确的结果hello 世界 。 我想知道我是否遗漏了代码中的某些内容,以及为什么会发生这种情况。 感谢你们。

我认为这篇文章与我的情况类似,但不完全一样。

问题在于字符集规范。 对我来说,它适用于这种变化:

 'Content-Type': 'text/plain;charset=utf-8' 

使用Chrome,Firefox和Safari进行testing。

您也可以查看node.js包中的“express”,它允许像这样重写代码:

 var express=require('express'); var app=express.createServer(); app.get('/',function(req, res) { var content = "Hello 世界"; res.charset = 'utf-8'; res.contentType('text'); res.send(content); }); app.listen(9002); 

content-encoding不是字符集,而是http响应本身的编码

charset不是一个常见的http头

content-length在这里是不必要的

正如@jjrv所说,你应该写'Content-Type': 'text/plain;charset=utf-8'

实际上在GB-18030中是世界编码,然后显示为UTF-8。 可能这些字符被保存在该编码中。

Interesting Posts