如何在 Node.js 中获取 UTF-8?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/16267274/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to get UTF-8 in Node.js?
提问by Hyman
How do I get UTF-8 support on my API? At the moment, a string outputs like this:
如何在我的 API 上获得 UTF-8 支持?目前,一个字符串输出如下:
name: "John D?m"
Instead of:
代替:
name: "John D?m"
Checkout app.js below:
在下面结帐 app.js:
var express = require('express'),
driver = require('./driver');
var app = express();
app.configure(function () {
app.use(express.logger('dev'));
app.use(express.bodyParser());
});
app.get('/drivers', driver.findAll);
app.listen(3000);
console.log('Up: http://127.0.0.1:3000/');
回答by TheHippo
Hook into you response generator or create a middleware that does the following:
连接到您的响应生成器或创建一个执行以下操作的中间件:
res.header("Content-Type", "application/json; charset=utf-8");
Otherwise the browser displays the content in his favorite encoding.
否则浏览器以他喜欢的编码显示内容。
If this doesn't help you DB is probably in the wrong encoding.
如果这对您没有帮助,则 DB 可能处于错误的编码中。
Edit:Since the answer is nearly 5 years old, the API has changed. For current node.js versions use:
编辑:由于答案已有近 5 年的历史,因此 API 发生了变化。对于当前的 node.js 版本,请使用:
res.setHeader("Content-Type", "application/json; charset=utf-8");
回答by Murat Ersin
I can't solve this problem with setting content type. I solved this problem with encode function.
我无法通过设置内容类型来解决这个问题。我用编码功能解决了这个问题。
res.cookie('someCookie', someCookie, {
encode: c => c,
});
For more information: express cookie
欲了解更多信息:快速饼干
ExpressJS version: 4.16.4
ExpressJS 版本:4.16.4
回答by Ehsan Ali
My problem solved with this:
我的问题是这样解决的:
res.writeHeader(200 , {"Content-Type" : "text/html; charset=utf-8"});
res.writeHeader(200 , {"Content-Type" : "text/html; charset=utf-8"});

