这是我的小代码:
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
发送“hello world”并且效果很好。然后我想稍微调整一下,将'world'改为中文对应的'世界',因此将标题中的'charset''content-type'更改为'utf-8'。但是在 Chrome 和 Firefox 中我看到了这个:
hello 涓栫晫
然而,令人惊讶的是,opera(11.61) 确实显示了正确的结果 hello 世界
。我想知道我是否遗漏了代码中的某些内容,以及为什么会这样。谢谢你们。
我认为this post与我的情况相似,但不完全。
最佳答案
问题出在字符集规范上。对我来说,它适用于这种变化:
'Content-Type': 'text/plain;charset=utf-8'
已在 Chrome、Firefox 和 Safari 上测试。
您还可以查看 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);
关于node.js - 为什么nodejs HTTP响应不能写汉字?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10470426/