node.js - 为什么nodejs HTTP响应不能写汉字?

标签 node.js utf-8 cjk

这是我的小代码:

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/

相关文章:

node.js - 尝试通过 --experimental-loader 选项使用 mocha、ES6 模块和 ts-node

node.js - 在 Windows Azure 上部署 Node/Express 应用程序时出错

javascript - 使用 Face-api.js 检测面部时出错预期媒体为 HTMLImageElement 类型 | HTMLVideo 元素 | HTMLCanvas元素

javascript - ajax javascript、nodejs、expressjs 的帖子发生多次

java - [] 如何改变 Java 正则表达式?

php - 如何使用 PHP 从字符串中截断非 ascii 字符

mysql - '𠂉' 不是有效的 unicode 字符,但在 unicode 字符集中?

ruby-on-rails - Paypal IPN : Invalid byte sequence in UTF-8

php - 将文本识别为简体中文和繁体中文

Python 编码日语字符