为什么我不能在nodejs HTTP响应中写汉字? [英] Why can't I write Chinese characters in nodejs HTTP response?
问题描述
这是我的小代码:
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",并且效果很好.然后我想稍作调整,将世界"更改为中文等效的世界",然后将标头中的字符集",内容类型"更改为"utf-8".但是在Chrome和Firefox中,我看到了这一点:
Previously I just let res.end
to send "hello world" and it worked well. Then I wanted to adjust a little bit and changed the 'world' into the Chinese equivalent '世界', and so changed the 'charset' 'content-type' in the header to 'utf-8'. But in Chrome and Firefox I see this:
hello 涓栫晫
但是,令人惊讶的是Opera(11.61)确实显示了正确的结果hello 世界
.我想知道我是否错过了代码中的某些内容,以及为什么会发生这种情况.谢谢你们.
However, amazingly opera(11.61) does show the correct result hello 世界
. I want to know whether I have missed something in the code, and why this is happening. Thank you guys.
我认为此帖子与我的情况类似,但不完全相同.
I think this post is similiar with my situation but not exactly.
推荐答案
问题在于字符集规范.对我来说,它适用于此更改:
Problem is with the character set specification. For me it works with this change:
'Content-Type': 'text/plain;charset=utf-8'
经过Chrome,Firefox和Safari的测试.
Tested with Chrome, Firefox and Safari.
您还可以查看node.js包"express",该包允许这样重写代码:
You could also look into the node.js package "express" which allows rewriting your code like this:
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);
这篇关于为什么我不能在nodejs HTTP响应中写汉字?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!